package com.mes.schedule.manager;


import java.io.StringReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.mes.basicdata.domain.Routing;
import com.mes.check.dao.RejectDao;
import com.mes.check.domain.Reject;
import com.mes.common.domain.BasicModel;
import com.mes.common.util.IdentityGenerator;
import com.mes.common.util.SysUtil;
import com.mes.prepare.domain.PrepareTask;
import com.mes.prepare.manager.PrepareTaskManager;
import com.mes.schedule.dao.SOperationTaskDao;
import com.mes.schedule.dao.STaskDao;
import com.mes.schedule.dao.ScheduleEventDao;
import com.mes.schedule.dao.ScheduleOperationRecordDao;
import com.mes.schedule.domain.SCoTask;
import com.mes.schedule.domain.SDevice;
import com.mes.schedule.domain.SGroupOperationTask;
import com.mes.schedule.domain.SOperationTask;
import com.mes.schedule.domain.SPartTask;
import com.mes.schedule.domain.ScheduleEvent;
import com.mes.schedule.domain.ScheduleOperationRecord;
import com.mes.schedule.domain.ScheduleScheme;
import com.mes.schedule.manager.iface.IScheduleSyncManager;
import com.mes.task.dao.OperationTaskDao;
import com.mes.task.dao.PartTaskDao;
import com.mes.task.dao.WorkRecordDao;
import com.mes.task.domain.OperationTask;
import com.mes.task.domain.PartTask;
import com.mes.task.domain.WorkRecord;
import com.mes.task.manager.OperationTaskManager;
import com.mes.task.manager.PartTaskManager;

@Component("scheduleSyncManager")
@Transactional
public class ScheduleSyncManager implements IScheduleSyncManager{
	private final static Log log = LogFactory
			.getLog(ScheduleSyncManager.class);
	 
	private PartTaskManager partTaskManager;
	 
	private OperationTaskManager operationTaskManager;
	 
	public ScheduleOperationTaskManager scheduleOperationTaskManager;
	 
	private ScheduleDeviceManager scheduleDeviceManager;
	 
	private SchedulePartTaskManager schedulePartTaskManager;
	/* @Resource(name="scheduleManage") */
	 
	private ScheduleManager scheduleManager;
	 
	private PartTaskDao partTaskDao;
	 
	private OperationTaskDao operationTaskDao;
	 
	private WorkRecordDao workRecordDao;
	 
	private STaskDao scheduleTaskDao;

	 
	private RejectDao rejectDao;

	 
	private ScheduleEventDao scheduleEventDao;
	 
	private PrepareTaskManager prepareTaskManager;

	 
	private ScheduleEventManager scheduleEventManager;

	 
	private ScheduleOperationRecordManager scheduleOperationRecordManager;

	 
	private ScheduleOperationRecordDao scheduleOperationRecordDao;

	 
	private ScheduleRoutingManager scheduleRoutingManager;
	
	private SOperationTaskDao sOperationTaskDao;
	

	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	 
	public String addPartTask(ScheduleScheme scheme) throws Exception {
		log.debug("开始同步新增任务" + scheme);
		List<SPartTask> newPartTasks = scheduleTaskDao.getNewPartTask(scheme);
		StringBuilder strResult = new StringBuilder();
		strResult.append("开始同步新增零组件任务信息：\n");
		// 缺省将其自动添加入调度系统
		// lqm todo
		// 应该参数化，用户提出要求新加入零件任务给一个醒目标识用户提出要求新加入零件任务给一个醒目标识
		int i = 0;
		if (newPartTasks != null && newPartTasks.size() > 0) {
			for (SPartTask sp : newPartTasks) {
				strResult.append(" 零组件任务 图号：" + sp.getDrawingId() + "批次："
						+ sp.getBatchNum());
				try {
					this.addSinglePartTask(scheme, sp);
					strResult.append(" 同步成功！" + " \n");
					i++;

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					strResult.append(" 同步失败！" + e.getMessage() + " \n");
				}

			}
		}

		// refreshCombineBatch(scheme);
		log.debug("结束同步新增任务" + scheme);
		return strResult.toString();
	}

	@Transactional(propagation = Propagation.REQUIRED)
	private void addSinglePartTask(ScheduleScheme scheme, SPartTask sp)
			throws Exception {

		Routing planRouting = this.scheduleRoutingManager
				.getDefaultPlanRouting(sp.getPartUid());
		if (planRouting == null) {
			// 按照以前的方式导入数据
			scheduleTaskDao.syncOperationTaskByPartTask(scheme, sp);
			scheduleTaskDao.syncOperationLinkByPartTask(scheme, sp);
		} else {
			// 按照新方式分解产生数据
			String currentOperationIdDesc = this.schedulePartTaskManager
					.getCurrentOperationIdDesc(scheme, sp);

			this.schedulePartTaskManager.applyRouting(scheme, sp, planRouting,
					currentOperationIdDesc);
		}

		scheme.getAllPartTaskMap().put(sp.getTaskUid(), sp);
		this.schedulePartTaskManager.add(sp);

		this.schedulePartTaskManager.init(scheme, sp);
		if (sp.getLateFinish() != null)
			this.schedulePartTaskManager.intoSchedule(sp);

	}

	private boolean isInScheduleTask(OperationTask o, SOperationTask so) {

		if (o.getPartUid().equals(so.getPartUid())) {
			if (so.getBatchNum().equals(o.getBatchNum())
					|| so.getBatchNum().startsWith(o.getBatchNum() + ",")
					|| so.getBatchNum().endsWith("," + o.getBatchNum())
					|| so.getBatchNum().indexOf("," + o.getBatchNum() + ",") > 0)
				if (so.getOperationIdDesc().equals(o.getOperationIdDesc())
						|| so.getOperationIdDesc().startsWith(
								o.getOperationIdDesc() + "/")
						|| so.getOperationIdDesc().endsWith(
								"/" + o.getOperationIdDesc())
						|| so.getOperationIdDesc().indexOf(
								"/" + o.getOperationIdDesc() + "/") > 0)
					return true;
		}
		return false;
	}

	// 获取原始任务
	private OperationTask getOriginTask(SOperationTask so) throws Exception {
		try {
			OperationTask oo = (OperationTask) operationTaskDao.getById(so
					.getTaskUid());
			if (oo != null) {// 原始任务
				return oo;
			} else {
				oo = (OperationTask) operationTaskDao.getOperationTask(so
						.getPartUid(), so.getBatchNum(), so
						.getOperationIdDesc());
				if (oo != null)
					return oo;
			}
		} catch (RuntimeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

	private SOperationTask getScheduleTask(ScheduleScheme scheme,
			String taskUid, Map<String, SOperationTask> OperationTaskKeyMap) throws Exception {
		if (scheme.getAllOperationTaskMap().containsKey(taskUid)) {
			return scheme.getAllOperationTaskMap().get(taskUid);
		}

		OperationTask operationTask = this.operationTaskDao.getById(taskUid);
		if (operationTask == null)
			return null;
		return this.getScheduleTask(scheme, operationTask, OperationTaskKeyMap);
	}

	private SOperationTask getScheduleTask(ScheduleScheme scheme,
			OperationTask operationTask,
			Map<String, SOperationTask> OperationTaskKeyMap) {
		SOperationTask so = null;
		if (scheme.getAllOperationTaskMap()
				.containsKey(operationTask.getUuid())) {
			so = scheme.getAllOperationTaskMap().get(operationTask.getUuid());

		} else {
			String strKey;
			try {
				strKey = operationTask.getPartUid() + "_"
						+ operationTask.getBatchNum() + "_"
						+ operationTask.getOperationIdDesc();
				so = OperationTaskKeyMap.get(strKey);
			} catch (RuntimeException e) {
				// TODO Auto-generated catch block
				log.warn("工序信息不完整，任务：" + operationTask);
				// e.printStackTrace();
			}

			// 通过关键字索引

			// // 对安排在当前时间+7天的任务优先处理,这样缩小范围
			// // todo
			// for (SOperationTask so : scheme.getAllOperationTaskMap()
			// .values()) {
			// if (isInScheduleTask(workRecord.getOperationTask(), so)) {
			// currentOperationTask = so;
			// break;
			// }
			// }
		}

		return so;
	}

	private SPartTask getScheduleTask(ScheduleScheme scheme, PartTask PartTask,
			Map<String, SPartTask> PartTaskKeyMap) {
		SPartTask so = null;
		if (scheme.getAllPartTaskMap().containsKey(PartTask.getUuid())) {
			so = scheme.getAllPartTaskMap().get(PartTask.getUuid());

		} else {
			String strKey;
			try {
				strKey = PartTask.getPartUid() + "_" + PartTask.getBatchNum();
				so = PartTaskKeyMap.get(strKey);
			} catch (RuntimeException e) {
				// TODO Auto-generated catch block
				log.warn("信息不完整，任务：" + PartTask);
				// e.printStackTrace();
			}

		}

		return so;
	}

	/**
	 * 是否所有子任务都已经完成
	 * 
	 * @param so
	 * @return
	 */
	private boolean isAllMemberFinish(SOperationTask so) {
		boolean bf = false;
		try {
			Set<OperationTask> ooSet = this.scheduleOperationTaskManager
					.getOOTasks(so);
			if (ooSet != null && ooSet.size() > 0) {
				bf = true;
				for (OperationTask o : ooSet) {
					if (o.isFinished()) {
						bf = false;
						break;
					}
				}
			}
		} catch (Exception e) {
			log.error("isAllMemberFinish", e);
		}

		return bf;
	}

	// 用事务主要是为了解决时间问题
	@Transactional
	 
	public String addWorkRecord(ScheduleScheme scheme,
			Map<String, SOperationTask> OperationTaskKeyMap) throws Exception {
		log.debug("开始同步加工进度");

		Date thisUpdateTime = new Date();

		StringBuilder strResult = new StringBuilder();
		strResult.append("开始同步加工进度信息\n");
		try {

			List<WorkRecord> workRecords = workRecordDao.getWorkRecords(scheme
					.getDeptUid(), scheme.getLastUpdateTime(), thisUpdateTime,
					null);

			int iCount = 0;

			if (workRecords != null && workRecords.size() > 0) {
				log.debug("总同步加工记录条数为：" + workRecords.size());
				// todo
				iCount = workRecords.size();
				for (WorkRecord workRecord : workRecords) {
					if (workRecord.getOperationTask() == null
							|| workRecord.getOperationTask().getTaskUid() == null)
						continue;
					SOperationTask currentOperationTask = getScheduleTask(
							scheme, workRecord.getOperationTask(),
							OperationTaskKeyMap);

					if (currentOperationTask == null)
						continue;
					// 如果设置任务开始加工
					String workType = "";
//					workRecord.getWorkType() == null ? "1"
//							: workRecord.getWorkType();
					// 缺省用当前时间
					Date workDate = workRecord.getWorkDate() == null ? (new Date())
							: workRecord.getWorkDate();

					String deviceName = "";
					if (workRecord.getDevice() != null)
						deviceName = workRecord.getDevice().getDeviceName()
								+ ", ";

					if (workType.equals("4")) {
						scheduleOperationTaskManager.completePrepare(scheme,
								currentOperationTask,
								workRecord.getDeviceUid(), workDate);
						strResult.append("    " + deviceName
								+ currentOperationTask.toFriendlyString()
								+ " 设置为已完成准备" + "\n");
						// currentOperationTask.setPlanStart();
					}
					if (workType.equals("3")) {
						// 207的任务应该拥有最高的优先权

						if (workRecord.getDeviceUid() != null
								&& !workRecord.getDeviceUid().equals(
										currentOperationTask.getDeviceUid()))
							currentOperationTask.setDeviceUid(workRecord
									.getDeviceUid());
						scheduleOperationTaskManager.startTask(scheme,
								currentOperationTask,
								workRecord.getDeviceUid(), workDate);
						;
						strResult.append("    " + deviceName
								+ currentOperationTask.toFriendlyString()
								+ " 设置为已开始" + "\n");
						// currentOperationTask.setPlanStart();
					}

					if (workType.equals("9")) {
						// 207的任务应该拥有最高的优先权

						if (workRecord.getDeviceUid() != null
								&& !workRecord.getDeviceUid().equals(
										currentOperationTask.getDeviceUid()))
							currentOperationTask.setDeviceUid(workRecord
									.getDeviceUid());
						scheduleOperationTaskManager.interruptTask(scheme,
								currentOperationTask, null, null, null);
						;
						strResult.append("    " + deviceName
								+ currentOperationTask.toFriendlyString()
								+ " 设置为已中断" + "\n");
						// currentOperationTask.setPlanStart();
					}
					if (workType.equals("8")) {
						// 207的任务应该拥有最高的优先权

						if (workRecord.getDeviceUid() != null
								&& !workRecord.getDeviceUid().equals(
										currentOperationTask.getDeviceUid()))
							currentOperationTask.setDeviceUid(workRecord
									.getDeviceUid());
						scheduleOperationTaskManager.pauseTask(scheme,
								currentOperationTask, null, null, null);
						;
						strResult.append("    " + deviceName
								+ currentOperationTask.toFriendlyString()
								+ " 设置为已暂停" + "\n");
						// currentOperationTask.setPlanStart();
					}
					if (workType.equals("6")) {

						// todo
						strResult.append("    " + deviceName
								+ currentOperationTask.toFriendlyString()
								+ " 设置为已完成首件检验" + "\n");
						this.scheduleOperationTaskManager.completeFirstCheck(
								scheme, currentOperationTask, workRecord
										.getDeviceUid(), workDate);
						// currentOperationTask.setPlanStart();
					}
					if (workRecord.getCompleteQty() != null
							&& workRecord.getCompleteQty() != 0) {

						if (currentOperationTask.isGroupTask()) {
							if (this.isAllMemberFinish(currentOperationTask))
								this.scheduleOperationTaskManager.completeTask(
										scheme, currentOperationTask);
							else {
								// 必须以该工序结尾才计数
								if (currentOperationTask.getOperationIdDesc()
										.endsWith(
												workRecord.getOperationTask()
														.getOperationIdDesc()))
									this.scheduleOperationTaskManager
											.feedbackQty(scheme,
													currentOperationTask,
													workRecord.getCompleteQty()
															.doubleValue(),
													workRecord.getDeviceUid(),
													workDate);
							}
						} else {
							// 采用这种方法保持与外面的参数一致
							if (workRecord.getOperationTask() != null
									&& workRecord.getOperationTask()
											.isFinished())
								this.scheduleOperationTaskManager.completeTask(
										scheme, currentOperationTask);
							else
								this.scheduleOperationTaskManager.feedbackQty(
										scheme, currentOperationTask,
										workRecord.getCompleteQty()
												.doubleValue(), workRecord
												.getDeviceUid(), workDate);
						}

						strResult.append("    " + deviceName
								+ currentOperationTask.toFriendlyString()
								+ " 完成数:" + workRecord.getCompleteQty() + "\n");

					}

					// 状态位引起设备状态发生变化
					this.scheduleOperationTaskManager
							.calcAlterResourceList(currentOperationTask);
				}

			}

			if (iCount > 0)
				strResult.append("本次同步加工进度" + iCount + "条记录\n");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("同步加工记录时发生错误", e);
		}

		// 设置调度更新时间，最后关闭调度时保存该时间
		scheme.setLastUpdateTime(thisUpdateTime);
		this.scheduleManager.update(scheme);
		return strResult.toString();
	}

	@Transactional
	 
	public String cancelPartTask(ScheduleScheme scheme) throws Exception {
		StringBuilder strResult = new StringBuilder();
		strResult.append("开始移除已完成/取消零组件任务！\n");
		List<SPartTask> toBeDeletedList = new ArrayList<SPartTask>();
		boolean isRemoveFromDB = false;
		for (SPartTask st : scheme.getAllPartTaskMap().values()) {
			try {
				if (st.getTaskScheduleType() == SPartTask.TASKSCHEDULETYPE_NORMAL) {
					PartTask partTask = (PartTask) partTaskManager.getById(st
							.getTaskUid());
					if (partTask != null) {
						if (partTask.getTaskState() == PartTask.TASKSTATE_COMPLETED
								|| partTask.getTaskState() == PartTask.TASKSTATE_CANCELED) {
							toBeDeletedList.add(st);
							if (partTask.getTaskState() == PartTask.TASKSTATE_COMPLETED) {
								isRemoveFromDB = false;
							} else {
								isRemoveFromDB = true;
							}
						}
					}
				}
			} catch (RuntimeException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		for (SPartTask partTask : toBeDeletedList) {
			this.schedulePartTaskManager.removePartTask(partTask,
					isRemoveFromDB);
			strResult.append(partTask.toFriendlyString()
					+ " 已经完成/已取消，系统将其移出调度；\n");
		}
		return strResult.toString();
	}

	 
	public String engineeringChange(ScheduleScheme scheme) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	 
	public String rejectparttask(ScheduleScheme scheme) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	/*
	 * 建立零件任务的part_number,batchnum map 便于快速查找
	 */
	private Map<String, SPartTask> initPartTaskMap(ScheduleScheme scheme) {
		Map<String, SPartTask> PartTaskMap = new HashMap<String, SPartTask>();
		for (SPartTask st : scheme.getAllPartTaskMap().values()) {
			try {
				if (st.getPartUid() != null && st.getBatchNum() != null) {
					String strKey = st.getPartUid() + "_" + st.getBatchNum();
					PartTaskMap.put(strKey, st);

				} else {
					log.warn("信息不完整，任务号：" + st);
				}
			} catch (RuntimeException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		return PartTaskMap;
	}

	/*
	 * 建立工序任务的part_number,batchnum,operation_iddesc map 便于快速查找
	 */
	private Map<String, SOperationTask> initOperationTaskMap(
			ScheduleScheme scheme) {
		Map<String, SOperationTask> OperationTaskMap = new HashMap<String, SOperationTask>();
		for (SOperationTask so : scheme.getAllOperationTaskMap().values()) {
			try {
				if (log.isDebugEnabled()) {
					if (so.getTaskUid().equals(
							"8dbf9025-1c69-4872-bf79-7da29994e5e0"))
						log.debug("aaaaaaaaaaaaaaa");
				}
				if (so.getPartUid() != null && so.getBatchNum() != null
						&& so.getOperationIdDesc() != null) {
					String[] strBatchNums = so.getBatchNum().split(",");
					String[] strOperations = so.getOperationIdDesc().split("/");
					for (int i = 0; i < strBatchNums.length; i++) {
						String strBatchNum = strBatchNums[i];

						// 只取第一道工序
						// String strKey = so.getPartUid() + "_" + strBatchNum
						// + "_" + strOperations[0];
						// OperationTaskMap.put(strKey, so);
						// 后面的工序都近来,反而会将状态混乱
						// 这样虽然会有最后一个零件的风险,但问题应该不大
						// todo
						for (int j = 0; j < strOperations.length; j++) {
							String strOperationIddesc = strOperations[j];

							String strKey = so.getPartUid() + "_" + strBatchNum
									+ "_" + strOperationIddesc;
							OperationTaskMap.put(strKey, so);
						}
						OperationTaskMap.put(so.getPartUid() + "_"
								+ so.getBatchNum() + "_"
								+ so.getOperationIdDesc(), so);
					}
				} else {
					log.warn("工序信息不完整，任务号：" + so);
				}
			} catch (RuntimeException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		return OperationTaskMap;
	}

	/**
	 * 处理零件任务计划数量的改变
	 * 
	 * @param partTaskUid
	 * @param scheme
	 * @return
	 * @throws Exception
	 */
	@Transactional
	public void synPartTaskPlanQty(String partTaskUid, ScheduleScheme scheme)
			throws Exception {
		PartTask originPartTask = this.partTaskDao.getById(partTaskUid);
		if (originPartTask == null)
			return;

		SPartTask sp = this.schedulePartTaskManager.getSchedulePartTask(scheme,
				originPartTask);

		if (sp == null)
			this.schedulePartTaskManager.changePartTaskQty(scheme, sp,
					originPartTask.getPlanQty().doubleValue());

	}

	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	 
	public String syncScheme(ScheduleScheme scheme) throws Exception {
		synchronized (scheme) {
			log.debug("开始同步协作任务安排信息" + scheme);
			StringBuilder strMsg = new StringBuilder();

			try {
				log.debug("开始同步新增零组件任务！");
				strMsg.append(this.addPartTask(scheme));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// 移除原因，太慢，已经由打开计划时自动过滤将其清除
			// try {
			// log.debug("开始移除已完成/取消零组件任务！");
			// strMsg.append(this.cancelPartTask(scheme));
			// } catch (Exception e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// }
			// 可能会新增任务
			Map<String, SOperationTask> OperationTaskMap = initOperationTaskMap(scheme);

			// log.debug("开始同步工作中心变更记录");
			// strMsg.append(this.updateAssnignmentWorkCenter(scheme,
			// thisUpdateTime,
			// OperationTaskMap));
			// 移除原因，效率太低
			// try {
			// log.debug("开始移除已完成工序任务");
			// strMsg.append(this.cancelOperationTask(scheme));
			// } catch (Exception e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// }
			// by lqm 2014-5-13
			// 已经由调度事件同步计划info取代
			// try {
			// log.debug("开始同步新增报废信息");
			// strMsg.append(this.addReject(scheme, thisUpdateTime,
			// OperationTaskMap));
			// } catch (Exception e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// }

			// try {
			// log.debug("开始同步设备状态");
			// // 应该有不同的刷新频率
			// strMsg.append(this.addDeviceRunLog(scheme, thisUpdateTime));
			// } catch (Exception e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// }

			try {
				log.debug("开始处理调度同步事件");
				// 应该有不同的刷新频率
				strMsg
						.append(this.syncScheduleEvents(scheme,
								OperationTaskMap));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			try {
				log.debug("开始同步反馈记录！");
				// 暂时先注释掉
				strMsg.append(this.addWorkRecord(scheme, OperationTaskMap));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// log.debug(SpringUtils.getBean("scheduleManage"));

			//
			// try {
			// log.debug("开始同步协作任务状态");
			// // 应该有不同的刷新频率
			// strMsg.append(this.syncCoInTask(scheme, thisUpdateTime));
			// } catch (Exception e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// }
			// try {
			// log.debug("开始同步委外任务的安排信息");
			// // 应该有不同的刷新频率
			// strMsg.append(this.syncCoOutTask(scheme, thisUpdateTime));
			// } catch (Exception e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// }
			//
			// try {
			// log.debug("开始同步交货期变更信息");
			// // 应该有不同的刷新频率
			// strMsg
			// .append(this.syncLateFinishChange(scheme,
			// thisUpdateTime));
			// } catch (Exception e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// }

			// refreshCombineBatch(scheme);

			log.debug("结束同步计划" + scheme);
			return strMsg.toString();
		}
	}

	// ScheduleEvent.EVENTTYPE_DEVICE_BEGINMAINT
	private String eventProScheduleBeginMaint(ScheduleScheme scheme,
			ScheduleEvent scheduleEvent, Document contentXml) {

		SimpleDateFormat formatDate = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		Element rootElement = contentXml.getRootElement();

		try {
			String deviceUid = rootElement.getAttributeValue("deviceUid");
			SDevice device = scheme.getDeviceMap().get(deviceUid);
			String pString = rootElement.getAttributeValue("planFinish");
			Date planFinish = formatDate.parse(pString);

			this.scheduleDeviceManager.beginMaint(device, planFinish);

			return "    设备 " + device.getDeviceName() + " 开始维修！预计恢复时间为:"
					+ pString;

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

	private String eventProScheduleResumeMaint(ScheduleScheme scheme,
			ScheduleEvent scheduleEvent, Document contentXml) {

		SimpleDateFormat formatDate = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		Element rootElement = contentXml.getRootElement();
		String strDate = rootElement.getText();
		Date dt;
		try {
			String deviceUid = rootElement.getAttributeValue("deviceUid");
			SDevice device = scheme.getDeviceMap().get(deviceUid);

			this.scheduleDeviceManager.recoveryMaint(device);
			return "    设备 " + device.getDeviceName() + " 恢复正常运行!";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

	 
	public String updateAssnignmentWorkCenter(ScheduleScheme scheme,
			Date thisUpdateTime, Map<String, SOperationTask> OperationTaskMap)
			throws Exception {
		StringBuilder strResult = new StringBuilder();
		// strResult.append("同步工作中心变更\n");
		// List<AssignmentWorkCenter> assignmentWorkCenters =
		// assignmentWorkCenterDao
		// .getAssignmentWorkCenters(scheme.getDeptUid(), scheme
		// .getLastUpdateTime(), thisUpdateTime, null, null);
		//
		// int iCount = 0;
		//
		// if (assignmentWorkCenters != null && assignmentWorkCenters.size() >
		// 0) {
		// // todo
		// iCount = assignmentWorkCenters.size();
		// for (AssignmentWorkCenter assignmentWorkCenter :
		// assignmentWorkCenters) {
		// SOperationTask currentOperationTask = getScheduleTask(scheme,
		// assignmentWorkCenter.getOperationTask(),
		// OperationTaskMap);
		//
		// if (currentOperationTask == null)
		// continue;
		// // 如果设置任务开始加工
		//
		// if (!assignmentWorkCenter.getWorkCenterUid().equals(
		// currentOperationTask.getDeviceClass())) {
		// String workCenterUid, workCenterName;
		// workCenterUid = assignmentWorkCenter.getWorkCenterUid();
		// workCenterName = assignmentWorkCenter.getWorkCenter()
		// .getWorkCenterName();
		// if (!assignmentWorkCenter.getWorkCenter().getDeptUid()
		// .startsWith(scheme.getDeptUid())) {
		//
		// } else {
		// workCenterUid = "cooperationCenter";
		// workCenterName = "外协中心";
		// }
		// this.scheduleOperationTaskManager
		// .replaceWorkCenter(scheme, currentOperationTask,
		// workCenterUid, workCenterName);
		// strResult.append(currentOperationTask.toFriendlyString()
		// + " 工作中心替换为"
		// + assignmentWorkCenter.getWorkCenter()
		// .getWorkCenterName() + "\n");
		// }
		// // currentOperationTask.setPlanStart();
		//
		// }
		//
		// }

		// strResult.append("本次同步工作中心变更" + iCount + "条记录\n");
		return strResult.toString();
	}

	@Transactional
	 
	public String addReject(ScheduleScheme scheme, Date thisUpdateTime,
			Map<String, SOperationTask> OperationTaskMap) throws Exception {
		List<Reject> Rejects = rejectDao.getRejects(scheme.getDeptUid(), scheme
				.getLastUpdateTime(), thisUpdateTime, null, null);
		StringBuilder strResult = new StringBuilder();
		strResult.append("开始同步新增报废记录\n");
		int iCount = 0;

		if (Rejects != null && Rejects.size() > 0) {
			// todo
			iCount = Rejects.size();
			for (Reject reject : Rejects) {
				SOperationTask currentOperationTask = getScheduleTask(scheme,
						reject.getOperationTask(), OperationTaskMap);

				if (currentOperationTask == null)
					continue;
				// 如果设置任务开始加工
				if (currentOperationTask.getParentTaskUid() != null)
					this.synPartTaskPlanQty(currentOperationTask
							.getParentTaskUid(), scheme);
				else {
					currentOperationTask.setPlanQty(reject.getOperationTask()
							.getPlanQty().doubleValue());
					sOperationTaskDao.update(currentOperationTask);
				}

				// this.scheduleOperationTaskManager.updateRejectQty(scheme,
				// currentOperationTask, reject.getRejectQty());
				strResult.append("    "
						+ currentOperationTask.toFriendlyString() + " 新增报废数"
						+ reject.getRejectQty() + "个\n");
			}
			// currentOperationTask.setPlanStart();
			strResult.append("本次同步新增报废" + iCount + "条记录\n");
		}

		return strResult.toString();

	}

	 
	public String publishScheme(ScheduleScheme scheme) throws Exception {

		return null;
	}

	 
	public String clearDispatchOrder(ScheduleScheme scheme) throws Exception {
		// // 更新派工信息
		// // 删除任务状态为“已派工”的派工记录
		// // 已开始的任务自动锁定
		// assignmentDeviceManager.deleteUnWorkAssn(scheme.getDeptUid());

		// 清除所有派工状态
		for (SOperationTask operationTask : scheme.getAllOperationTaskMap()
				.values()) {
			if (operationTask.getTaskState() == SOperationTask.TASKSTATE_DISPATCHED)
				this.scheduleOperationTaskManager.cancelDispatchTask(scheme,
						operationTask);

		}
		return null;
	}

	 
	public String clearPlanTime(ScheduleScheme scheme) throws Exception {

		List<PartTask> wipPartTaskList = partTaskDao.getWipPartTasks(scheme
				.getDeptUid(), null, null);
		if (wipPartTaskList != null && wipPartTaskList.size() > 0) {
			for (PartTask partTask : wipPartTaskList) {

				partTask.setPlanStart(null);
				partTask.setPlanFinish(null);

			}
			partTaskManager.update(wipPartTaskList);
		}

		// Map<String, SOperationTask> operationTaskMap =
		// initOperationTaskMap(scheme);
		//
		// List<OperationTask> wipOperationTaskList = operationTaskDao
		// .getWipOperationTasks(scheme.getDeptUid(), null, null);
		// if (wipOperationTaskList != null && wipOperationTaskList.size() > 0)
		// {
		// for (OperationTask operationTask : wipOperationTaskList) {
		//
		// operationTask.setPlanStart(null);
		// operationTask.setPlanFinish(null);
		//
		// }
		// operationTaskManager.update(wipOperationTaskList);
		// }

		return null;
	}

	 
	public String clearPrepareOrder(ScheduleScheme scheme) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	private int getTimeOffsetMinutes(Date dt1, Date dt2) {
		return (int) Math.abs((dt1.getTime() - dt2.getTime()) / 60000);
	}

	// private void saveOrUpdatePrepareTask(SOperationTask so) throws Exception
	// {
	// /*
	// * 任选一个任务与其关联
	// */
	// Set<OperationTask> ooSet = this.scheduleOperationTaskManager
	// .getOOTasks(so);
	// if (ooSet == null || !ooSet.iterator().hasNext())
	// return;
	//
	// /*
	// * 任选一个任务与其关联
	// */
	// OperationTask oo = ooSet.iterator().next();
	//
	// // PrepareTask prepareTask = new PrepareTask();
	// // //直接用任务号作为
	// // prepareTask.setPrepareTaskUid(IdentityGenerator.GetIdentityUUID());
	// // prepareTask.setPrepareTaskType("301");
	// // prepareTask.setPrepareTaskState("205");
	// // prepareTask.setResuid(so.getDeviceUid());
	// // prepareTask.setTaskPlanStart(so.getPlanStart());
	// // prepareTask.setFinalTime(so.getPlanStart());
	// // prepareTask.setTaskBatchnum(so.getBatchNum());
	// // prepareTask.setTaskPartNumber(so.getPartUid());
	// //
	// //
	// //
	// // prepareTask.setPriority(0l);
	// // prepareTask.setOperationId((double) so.getOperationId());
	// // prepareTask.setOperationIddesc(so.getOperationIdDesc());
	// // prepareTask.setTaskDrawingid(so.getDrawingId());
	// //
	// // prepareTask.setRouting(oo.getRoutingUid());
	// // prepareTask.setOpuid(oo.getOperationUid());
	// //
	// //
	// // prepareTask.setTaskUid(oo.getUuid());
	// // prepareTask.setScheduleTaskUid(so.getTaskUid());
	// //
	// // this.prepareTaskManager.saveOrUpdateSortTask(prepareTask);
	// String creatorUid = MMUtils.getSessionEmployeeId();
	// this.prepareTaskManager.saveOrUpdatePrepareTask(so.getTaskUid(), oo
	// .getUuid(), creatorUid);
	// }

	private void saveOrUpdateCheckTask(SOperationTask so) throws Exception {
		PrepareTask prepareTask = new PrepareTask();

		prepareTask.setPrepareTaskUid(IdentityGenerator.GetIdentityUUID());
		prepareTask.setPrepareTaskType("301");
		prepareTask.setPrepareTaskState("205");
		prepareTask.setResuid(so.getDeviceUid());
		prepareTask.setTaskPlanStart(so.getPlanStart());
		prepareTask.setFinalTime(so.getPlanStart());
		prepareTask.setTaskBatchnum(so.getBatchNum());
		prepareTask.setTaskPartNumber(so.getPartUid());
		prepareTask.setOpuid(so.getOpUid());
		prepareTask.setTaskUid(so.getTaskUid());
		prepareTask.setPriority(0l);
		prepareTask.setOperationId((double) so.getOperationId());
		prepareTask.setOperationIddesc(so.getOperationIdDesc());
		prepareTask.setTaskDrawingid(so.getDrawingId());

//		this.prepareTaskManager.saveOrUpdateSortTask(prepareTask);
	}

	/*
	 * 派工记录重生成法
	 */

	 
	public String publishPrepareOrder(ScheduleScheme scheme) throws Exception {
		synchronized (scheme) {
			String creatorUid = "";//SysUtil.getSessionEmployeeId();
			// this.clearDispatchOrder(scheme);
//			prepareTaskManager.deleteUnStartPrepareTask();

			// 更新派工信息
			// 当前时间加上自动派工时间
			Calendar calendar = Calendar.getInstance();
			// int dispatchDays = scheme.getDispatchDays() == null ? 3 : scheme
			// .getDispatchDays();
			int dispatchDays = 2;
			calendar.add(Calendar.DATE, dispatchDays);
			Date dispatchDate = calendar.getTime();

			// 取得已经派工的所有对象

			for (SOperationTask so : scheme.getScheduleOperationTasks()) {
				if (so.getAssignState() == SOperationTask.ASSNSTATE_SUCCESS
						&& so.getPlanStart() != null
						&& so.getPlanFinish() != null
						&& so.getMasterShop() != null
						&& so.getMasterShop().equals(scheme.getDeptUid())
						&& so.getPlanStart().before(dispatchDate)) {

					this.scheduleOperationTaskManager.saveOrUpdatePrepareTask(
							so, null);

				}
			}
			return null;
		}
	}

	/*
	 * 产生检验任务
	 */
	private void publihCheckOrder(SOperationTask operationTask) {

	}

	/*
	 * 产生检验任务
	 */
	private void publihPlanInfo(SOperationTask operationTask) throws Exception {

		if (operationTask instanceof SGroupOperationTask) {
			SGroupOperationTask groupTask = (SGroupOperationTask) operationTask;
			List<SOperationTask> memberTasks = groupTask.getMemberTasks();
			if (memberTasks != null && memberTasks.size() > 0) {
				for (SOperationTask memberTask : memberTasks) {
					this.publihPlanInfo(memberTask);
				}
			}
			return;
		}

		// TODO Auto-generated method stub
		OperationTask oo = this.scheduleOperationTaskManager
				.getOOTask(operationTask);

		// 创建一个任务
		if (oo == null) {
			oo = new OperationTask();
			oo.setUuid(operationTask.getTaskUid());
			oo.setPartUid(operationTask.getPartUid());
			oo.setBatchNum(operationTask.getBatchNum());
			oo.setOperationIdDesc(operationTask.getOperationIdDesc());
			oo.setTaskName(operationTask.getTaskName());
//			oo.setTaskState((long)operationTask.TASKSTATE_READY);
			oo.setTaskType(operationTask.TASKTYPE_TEMPTASK);
			oo.setMasterShopUid(operationTask.getDeptUid());
			oo.setDeptUid(operationTask.getDeptUid());
//			oo.setPlanQty(operationTask
//					.getPlanQty().doubleValue());
			this.operationTaskManager.add(oo);

		}

		oo.setPlanStart(operationTask.getPlanStart());
		oo.setPlanFinish(operationTask.getPlanFinish());
		// 锁定任务不修改优先级
//		if (oo.getIsLocked() == null || !oo.getIsLocked())
//			oo.setPriority((long)operationTask.getPriority());
		this.operationTaskManager.add(oo);
	}

	/*
	 * 用于临时清除在MES中已完成任务,
	 */
	 
	public void clearFinishedTask(ScheduleScheme scheme) throws Exception {
		synchronized (scheme) {
			List<SOperationTask> ops = new ArrayList<SOperationTask>();
			for (SOperationTask so : scheme.getAllOperationTaskMap().values()) {
				ops.add(so);
			}

			for (SOperationTask so : ops) {
				try {
					Set<OperationTask> ooTaskSet = this.scheduleOperationTaskManager
							.getOOTasks(so);
					if (ooTaskSet != null && ooTaskSet.size() > 0) {
						boolean isFinished = true;
						for (OperationTask ooTask : ooTaskSet) {
							if (!ooTask.isFinished()) {
								isFinished = false;
								break;
							}
						}

						if (isFinished)
							this.scheduleOperationTaskManager
									.removeOperationTask(so, false);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		}

	}

	/*
	 * 派工记录重生成法
	 */
	 
	public String publishDispatchOrderTime(ScheduleScheme scheme)
			throws Exception {
		synchronized (scheme) {
			String creatorUid = "";//SysUtil.getSessionEmployeeId();

			// 取得已经派工的所有对象

			for (SOperationTask so : scheme.getScheduleOperationTasks()) {
				if (so.isRunning()
						&& so.getAssignState() == SOperationTask.ASSNSTATE_SUCCESS
						&& so.getPlanStart() != null
						&& so.getPlanFinish() != null
						&& so.getMasterShop() != null
						&& so.getMasterShop().equals(scheme.getDeptUid())
						&& so.getDevice() != null
						&& so.getDevice() != scheme.getVirtualCoDevice()) {
					Set<OperationTask> ooTaskSet = this.scheduleOperationTaskManager
							.getOOTasks(so);
					if (ooTaskSet != null && ooTaskSet.size() > 0) {
						for (OperationTask ooTask : ooTaskSet) {

							ooTask.setPlanStart(so.getPlanStart());
							ooTask.setPlanFinish(so.getPlanFinish());

						}
						operationTaskManager.update(ooTaskSet);
					}

				}

				// 发布派工指令同时发布生产准备指令

				// 对用pad自己领取任务没有设置好

			}
			return null;
		}
	}

	 
	/*
	 * 派工记录重生成法
	 */
	public String publishDispatchOrder(ScheduleScheme scheme) throws Exception {
		synchronized (scheme) {
			String creatorUid = "";//SysUtil.getSessionEmployeeId();
			// this.clearDispatchOrder(scheme);
			// 清除已经下达的生产准备指令
			// prepareTaskManager.deleteUnStartPrepareTask();
			// 更新派工信息
			// 当前时间加上自动派工时间
			Calendar calendar = Calendar.getInstance();
			int dispatchDays = scheme.getDispatchDays() == null ? 3 : scheme
					.getDispatchDays();
			calendar.add(Calendar.DATE, dispatchDays);
			Date dispatchDate = calendar.getTime();

			// 取得已经派工的所有对象

			for (SOperationTask so : scheme.getScheduleOperationTasks()) {
				if (so.getAssignState() == SOperationTask.ASSNSTATE_SUCCESS
						&& so.getPlanStart() != null
						&& so.getPlanFinish() != null
						&& so.getMasterShop() != null
						&& so.getMasterShop().equals(scheme.getDeptUid())
						&& so.getDevice() != null
						&& so.getDevice() != scheme.getVirtualCoDevice()) {

					if (so.getPlanStart().before(dispatchDate)) {
						// if(so.getTaskState()==SOperationTask.TASKSTATE_DISPATCHED)//更新派工任务
						//								
						// else
						// 更新工序任务的时间
						// this.publihPlanInfo(so);

						this.scheduleOperationTaskManager.dispatchTask(scheme,
								so);// 新增派工任务时会自动更新任务
						// lqmtodo 添加生产准备任务，这里没有完成更新操作
						// 临时判断，不完整
						// by lqm todo
						// if (so.getDevice().getCriticalLevel() < 6)
						// saveOrUpdatePrepareTask(so);
					} else if (so.getTaskState().equals(
							SOperationTask.TASKSTATE_DISPATCHED))// 对任务排出出scheduletasks调度集合未处理好
					{
						this.scheduleOperationTaskManager.cancelDispatchTask(
								scheme, so);// 取消派工任务
						// this.prepareTaskManager
						// .cancelPrepareTaskByScheduleTaskUid(so
						// .getTaskUid());
					}

				}

				// 发布派工指令同时发布生产准备指令

				// 对用pad自己领取任务没有设置好

			}
			return null;
		}
	}

	/*
	 * 派工记录尽改变法，还没有完善 (non-Javadoc)
	 * 
	 * @see com.mes.schedule.manager.iface.ScheduleSyncManager#publishDispatchOrder(com.mes.schedule.persistence.domain.ScheduleScheme)
	 */
	// public String publishDispatchOrder(ScheduleScheme scheme) throws
	// Exception {
	// String creatorUid = MMUtils.getSessionEmployeeId();
	// // this.clearDispatchOrder(scheme);
	// // 更新派工信息
	// //当前时间加上自动派工时间
	// Calendar calendar = Calendar.getInstance();
	// int dispatchDays = scheme.getDispatchDays() == null ? 3 : scheme
	// .getDispatchDays();
	// calendar.add(Calendar.DATE, dispatchDays);
	// Date dispatchDate = calendar.getTime();
	//
	// // 取得已经派工的所有对象
	// List<AssignmentDevice> assignmentDeviceList = (List<AssignmentDevice>)
	// assignmentDeviceDao
	// .getStartedAssignmentDevices(scheme.getDeptUid(), null);
	// Map<String, AssignmentDevice> assignmentDeviceMap = new HashMap<String,
	// AssignmentDevice>();
	// if (assignmentDeviceList != null && assignmentDeviceList.size() > 0) {
	// for (AssignmentDevice ad : assignmentDeviceList) {
	// assignmentDeviceMap.put(ad.getTaskUid(), ad);
	// }
	// }
	// for (SOperationTask so : scheme.getScheduleOperationTasks()) {
	// AssignmentDevice assignmentDevice = null;
	// if (so.getAssignState() == SOperationTask.ASSNSTATE_SUCCESS
	// && so.getPlanStart() != null &&so.getPlanFinish()!=null&&
	// so.getMasterShop() != null
	// && so.getMasterShop().equals(scheme.getDeptUid())
	// && so.getPlanStart().before(dispatchDate)) {
	//				
	// if (assignmentDeviceMap.containsKey(so.getTaskUid())) {
	// assignmentDevice = assignmentDeviceMap.get(so.getTaskUid());
	// if (assignmentDevice.getDeviceUid().equals(
	// so.getDeviceUid())) {
	// // 时间差异在一小时才更新
	// if(!(assignmentDevice.getAssnStart()!=null&&assignmentDevice.getAssnFinish()!=null
	// &&getTimeOffsetMinutes(so.getPlanStart(),
	// assignmentDevice.getAssnStart())<60
	// &&getTimeOffsetMinutes(so.getPlanFinish(),
	// assignmentDevice.getAssnFinish())<60 ))
	// {
	// assignmentDevice.setAssnStart(so.getPlanStart());
	// assignmentDevice.setAssnFinish(so.getPlanFinish());
	// assignmentDeviceManager.update(assignmentDevice);
	// log.info("调度自动发布，更改任务派工时间"+so.toFriendlyString());
	// }
	// } else {
	//						
	// assignmentDeviceManager.cancelAssn(assignmentDevice);
	// // 取消派工应该抛出事件
	// this.scheduleOperationTaskManager.cancelDispatchTask(scheme, so);
	// this.getScheduleOperationTaskManager().dispatchTask(scheme, so);
	//
	// this.getScheduleOperationTaskManager().dispatchTask(scheme, so);
	// log.info("调度自动发布，任务改派到其它设备间"+so.toFriendlyString());
	// }
	//
	// } else {
	// this.getScheduleOperationTaskManager().dispatchTask(scheme, so);
	// // // todo 20
	// // assignmentDeviceManager.addAssn(so.getTaskUid(), so
	// // .getDeviceUid(), null, so.getPlanStart(), so
	// // .getPlanFinish(), Double.valueOf(String.valueOf(so
	// // .getPlanQty())), creatorUid);
	// log.info("调度自动发布，新增任务派工"+so.toFriendlyString());
	//
	// }
	// }
	// }
	// return null;
	// }
	 
	public String publishPlanTime(ScheduleScheme scheme) throws Exception {

		Map<String, SPartTask> sPartTaskMap = initPartTaskMap(scheme);

		List<PartTask> wipPartTaskList = partTaskDao.getWipPartTasks(scheme
				.getDeptUid(), null, null);
		if (wipPartTaskList != null && wipPartTaskList.size() > 0) {
			for (PartTask partTask : wipPartTaskList) {
				SPartTask sPartTask = getScheduleTask(scheme, partTask,
						sPartTaskMap);
				if (sPartTask != null) {
					partTask.setPlanStart(sPartTask.getPlanStart());
					partTask.setPlanFinish(sPartTask.getPlanFinish());
//					partTask.setSlackFactor(sPartTask.getSlackFactor());
//					partTask.setPriority(sPartTask.getPriority().longValue());
				}
			}
			partTaskManager.update(wipPartTaskList);
		}

		// 提高速度
		// lqm todo
		// 这个太耗时了
		Map<String, SOperationTask> operationTaskMap = initOperationTaskMap(scheme);

		List<OperationTask> wipOperationTaskList = operationTaskDao
				.getWipOperationTasks(scheme.getDeptUid(), null, null);
		if (wipOperationTaskList != null && wipOperationTaskList.size() > 0) {
			for (OperationTask OperationTask : wipOperationTaskList) {
				SOperationTask sOperationTask = getScheduleTask(scheme,
						OperationTask, operationTaskMap);
				if (sOperationTask != null
						&& sOperationTask.getAssignState().equals(
								SOperationTask.ASSNSTATE_SUCCESS)) {

					OperationTask.setPlanStart(sOperationTask.getPlanStart());
					OperationTask.setPlanFinish(sOperationTask.getPlanFinish());

				}
			}
			operationTaskManager.update(wipOperationTaskList);
		}

		return null;

	}

	 
	public String publishScheme(ScheduleScheme scheme, String publishType)
			throws Exception {

		synchronized (scheme) {
			// TODO Auto-generated method stub
			if ("publishDispatchOrder".equals(publishType))
				this.publishDispatchOrder(scheme);
			if ("publishDispatchOrderTime".equals(publishType))
				this.publishDispatchOrderTime(scheme);
			else if ("clearDispatchOrder".equals(publishType))
				this.clearDispatchOrder(scheme);
			else if ("publishPlanTime".equals(publishType))
				this.publishPlanTime(scheme);
			else if ("clearPlanTime".equals(publishType))
				this.clearPlanTime(scheme);
			else if ("publishPrepareOrder".equals(publishType))
				this.publishPrepareOrder(scheme);
			else if ("clearPrepareOrder".equals(publishType))
				this.clearPrepareOrder(scheme);
			else if ("publishBasePlan".equals(publishType))
				this.publishBasePlan(scheme);
			else
				throw new Exception("不正确的计划发布类型！");
			return null;
		}
	}

	 
	public String publishBasePlan(ScheduleScheme scheme) throws Exception {
		for (SOperationTask opTask : scheme.getScheduleOperationTasks()) {
			opTask.setBaseStart(opTask.getPlanStart());
			opTask.setBaseFinish(opTask.getPlanFinish());
			sOperationTaskDao.update(opTask);
		}
		return null;
	}

	@Transactional
	 
	public String cancelOperationTask(ScheduleScheme scheme) throws Exception {
		StringBuilder strResult = new StringBuilder();
		strResult.append("移除已完成工序任务：\n");
		List<SOperationTask> tobeDeletedList = new ArrayList<SOperationTask>();
		try {
			for (SOperationTask so : scheme.getAllOperationTaskMap().values()) {
				if (so.getTaskScheduleType() == SOperationTask.TASKSCHEDULETYPE_NORMAL) {
					OperationTask oo = this.getOriginTask(so);
					if (oo != null
							&& oo.getTaskState() >= OperationTask.TASKSTATE_COMPLETED) {
						tobeDeletedList.add(so);

					}
				}
			}

			for (SOperationTask so : tobeDeletedList) {
				this.scheduleOperationTaskManager
						.removeOperationTask(so, false);
				strResult.append(so.toFriendlyString() + " 已经完成，系统将其移出调度；\n");
			}
			strResult.append("本次同步共移除已完成任务" + tobeDeletedList.size() + "条\n");
			tobeDeletedList = null;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return strResult.toString();
	}

	//  
	// public String syncCoInTask(ScheduleScheme scheme, Date thisUpdateTime)
	// throws Exception {
	// // TODO Auto-generated method stub
	// SAXBuilder sb = new SAXBuilder(false);
	// StringBuilder strResult = new StringBuilder();
	// strResult.append("开始同步协作任务信息：\n");
	// int n = 0;
	//
	// List<ScheduleEvent> scheduleEventList = (List<ScheduleEvent>)
	// scheduleEventDao
	// .getUnHandleEvents(scheme.getScheduleUid(),
	// ScheduleEvent.EVENTTYPE_PUBLISH_COTASK, scheme
	// .getLastUpdateTime(), thisUpdateTime, null);
	// if (scheduleEventList != null && scheduleEventList.size() > 0) {
	// SimpleDateFormat formatDate = new SimpleDateFormat(
	// "yyyy-MM-dd HH:mm:ss");
	// for (ScheduleEvent scheduleEvent : scheduleEventList) {
	// try {
	// String strXml = scheduleEvent.getEventContent();
	// StringReader read = new StringReader(strXml);
	// Document doc = sb.build(read);
	//
	// Element rootElement = doc.getRootElement();
	// String taskUid = rootElement.getAttributeValue("taskUid");
	// SCoTask co;
	// if (scheme.getCoTaskMap().containsKey(taskUid)) {
	// co = (SCoTask) scheme.getCoTaskMap().get(taskUid);
	// } else {
	// co = new SCoTask();
	//
	// co.setTaskUid(taskUid);
	//
	// co.setTaskName(rootElement
	// .getAttributeValue("taskName"));
	// co.setPartUid(rootElement.getAttributeValue("partUid"));
	// co.setDrawingId(rootElement
	// .getAttributeValue("drawingId"));
	// co.setPartName(rootElement
	// .getAttributeValue("partName"));
	// co.setBatchNum(rootElement
	// .getAttributeValue("batchNum"));
	// co.setOperationIdDesc(rootElement
	// .getAttributeValue("operationIdDesc"));
	// co.setDeviceClass(rootElement
	// .getAttributeValue("deviceClass"));
	// co.setDeviceClassName(rootElement
	// .getAttributeValue("deviceClassName"));
	// co.setDeptUid(rootElement.getAttributeValue("deptUid"));
	// co.setDeptName(rootElement
	// .getAttributeValue("deptName"));
	// co.setMasterShop(rootElement
	// .getAttributeValue("masterShop"));
	// co.setMasterShopName(rootElement
	// .getAttributeValue("masterShopName"));
	// co.setOpUid(rootElement.getAttributeValue("opUid"));
	// co.setPlanGrade(Integer.valueOf(rootElement
	// .getAttributeValue("planGrade")));
	//
	// co.setEstiPreTime(Double.valueOf(rootElement
	// .getAttributeValue("estiPreTime")));
	// co.setEstiRunTime(Double.valueOf(rootElement
	// .getAttributeValue("estiRunTime")));
	// }
	// co.setPlanQty(Double.valueOf(rootElement
	// .getAttributeValue("planQty")));
	// co.setCompleteQty(Double.valueOf(rootElement
	// .getAttributeValue("completeQty")));
	// co.setEarlyStart(formatDate.parse(rootElement
	// .getAttributeValue("earlyStart")));
	// co.setLateFinish(formatDate.parse(rootElement
	// .getAttributeValue("lateFinish")));
	// co.setNotes(rootElement.getAttributeValue("notes"));
	//
	// this.scheduleOperationTaskManager.addOperationTask(scheme,
	// co);
	//
	// scheduleEvent
	// .setEventState(ScheduleEvent.EVENTSTATE_SUCCESS);
	// strResult.append(" 新增协作任务:" + co.toFriendlyString()
	// + "\n");
	// n++;
	// } catch (RuntimeException e) {
	// scheduleEvent
	// .setEventState(ScheduleEvent.EVENTSTATE_FAILURE);
	// e.printStackTrace();
	// }
	//
	// scheduleEvent.setHandler(MMUtils.getSessionEmployeeId());
	// scheduleEvent.setHandleTime(new Date());
	//				
	// this.scheduleEventManager.update(scheduleEvent);
	//
	//
	//
	// // Iterator iter=rootElement.getChildren().iterator();
	// // while(iter.hasNext())
	// // {
	// // Element taskElement=(Element)iter.next();
	// //
	// //
	// // }
	// }
	// strResult.append("本次同步新增协作任务" + n + "条\n");
	// }
	//
	// scheduleEventList = (List<ScheduleEvent>) scheduleEventDao
	// .getUnHandleEvents(scheme.getScheduleUid(),
	// ScheduleEvent.EVENTTYPE_UNPUBLISH_COTASK, scheme
	// .getLastUpdateTime(), thisUpdateTime, null);
	// n = 0;
	// if (scheduleEventList != null && scheduleEventList.size() > 0) {
	//
	// for (ScheduleEvent scheduleEvent : scheduleEventList) {
	// try {
	// String strXml = scheduleEvent.getEventContent();
	// StringReader read = new StringReader(strXml);
	// Document doc = sb.build(read);
	//
	// Element rootElement = doc.getRootElement();
	// String taskUid = rootElement.getAttributeValue("taskUid");
	// SCoTask co;
	// if (scheme.getCoTaskMap().containsKey(taskUid)) {
	// co = (SCoTask) scheme.getCoTaskMap().get(taskUid);
	// this.scheduleOperationTaskManager
	// .removeOperationTask(co);
	//
	// scheduleEvent
	// .setEventState(ScheduleEvent.EVENTSTATE_SUCCESS);
	// strResult.append(" 取消协作任务:" + co.toFriendlyString()
	// + "\n");
	// n++;
	// }
	// } catch (RuntimeException e) {
	// scheduleEvent
	// .setEventState(ScheduleEvent.EVENTSTATE_FAILURE);
	// e.printStackTrace();
	// }
	//
	// scheduleEvent.setHandler(MMUtils.getSessionEmployeeId());
	// scheduleEvent.setHandleTime(new Date());
	//
	// //scheme.getProcessedEventList().add(scheduleEvent);
	//
	// // Iterator iter=rootElement.getChildren().iterator();
	// // while(iter.hasNext())
	// // {
	// // Element taskElement=(Element)iter.next();
	// //
	// //
	// // }
	// }
	// strResult.append("本次取消协作任务" + n + "条\n");
	// }
	//
	// return strResult.toString();
	// }
	//
	//  
	// public String syncCoOutTask(ScheduleScheme scheme, Date thisUpdateTime)
	// throws Exception {
	//
	// // TODO Auto-generated method stub
	// SAXBuilder sb = new SAXBuilder(false);
	// StringBuilder strResult = new StringBuilder();
	// strResult.append("开始同步委外任务信息：\n");
	// int n = 0;
	//
	// List<ScheduleEvent> scheduleEventList = (List<ScheduleEvent>)
	// scheduleEventDao
	// .getUnHandleEvents(scheme.getScheduleUid(),
	// ScheduleEvent.EVENTTYPE_FEEDBACK_COTASK, scheme
	// .getLastUpdateTime(), thisUpdateTime, null);
	// if (scheduleEventList != null && scheduleEventList.size() > 0) {
	// SimpleDateFormat formatDate = new SimpleDateFormat(
	// "yyyy-MM-dd HH:mm:ss");
	// for (ScheduleEvent scheduleEvent : scheduleEventList) {
	// try {
	// String strXml = scheduleEvent.getEventContent();
	// StringReader read = new StringReader(strXml);
	// Document doc = sb.build(read);
	//
	// Element rootElement = doc.getRootElement();
	// String taskUid = rootElement.getAttributeValue("taskUid");
	// SOperationTask co = scheme.getAllOperationTaskMap().get(
	// taskUid);
	// if (co != null
	// && rootElement.getAttributeValue("planStart") != null
	// && rootElement.getAttributeValue("planFinish") != null) {
	// co.setPlanStart(formatDate.parse(rootElement
	// .getAttributeValue("planStart")));
	// co.setPlanFinish(formatDate.parse(rootElement
	// .getAttributeValue("planFinish")));
	// co.setNotes(rootElement.getAttributeValue("notes"));
	// co
	// .setCoTaskState(SOperationTask.COTASKSTATE_FEEDBACKED);
	// co.setLocked(1); // 协作任务自动设置为锁定
	// strResult.append(" 委外任务:" + co.toFriendlyString()
	// + "\n");
	// }
	// scheduleEvent
	// .setEventState(ScheduleEvent.EVENTSTATE_SUCCESS);
	// n++;
	// } catch (RuntimeException e) {
	// scheduleEvent
	// .setEventState(ScheduleEvent.EVENTSTATE_FAILURE);
	// e.printStackTrace();
	// }
	//
	// scheduleEvent.setHandler(MMUtils.getSessionEmployeeId());
	// scheduleEvent.setHandleTime(new Date());
	//
	// // scheme.getProcessedEventList().add(scheduleEvent);
	//
	// // Iterator iter=rootElement.getChildren().iterator();
	// // while(iter.hasNext())
	// // {
	// // Element taskElement=(Element)iter.next();
	// //
	// //
	// // }
	// }
	// strResult.append(" 本次同步委外任务反馈信息" + n + "条\n");
	// }
	//
	// n = 0;
	//
	// scheduleEventList = (List<ScheduleEvent>) scheduleEventDao
	// .getUnHandleEvents(scheme.getScheduleUid(),
	// ScheduleEvent.EVENTTYPE_RECEIVE_COTASK, scheme
	// .getLastUpdateTime(), thisUpdateTime, null);
	// if (scheduleEventList != null && scheduleEventList.size() > 0) {
	// SimpleDateFormat formatDate = new SimpleDateFormat(
	// "yyyy-MM-dd HH:mm:ss");
	// for (ScheduleEvent scheduleEvent : scheduleEventList) {
	// try {
	// String strXml = scheduleEvent.getEventContent();
	// StringReader read = new StringReader(strXml);
	// Document doc = sb.build(read);
	//
	// Element rootElement = doc.getRootElement();
	// String taskUid = rootElement.getAttributeValue("taskUid");
	// SOperationTask co = scheme.getAllOperationTaskMap().get(
	// taskUid);
	//
	// co.setNotes(rootElement.getAttributeValue("notes"));
	// co.setCoTaskState(SOperationTask.COTASKSTATE_RECEIVED);
	// strResult.append(" 委外任务已接收:" + co.toFriendlyString()
	// + "\n");
	//
	// scheduleEvent
	// .setEventState(ScheduleEvent.EVENTSTATE_SUCCESS);
	// n++;
	// } catch (RuntimeException e) {
	// scheduleEvent
	// .setEventState(ScheduleEvent.EVENTSTATE_FAILURE);
	// e.printStackTrace();
	// }
	//
	// scheduleEvent.setHandler(MMUtils.getSessionEmployeeId());
	// scheduleEvent.setHandleTime(new Date());
	//
	// // scheme.getProcessedEventList().add(scheduleEvent);
	//
	// // Iterator iter=rootElement.getChildren().iterator();
	// // while(iter.hasNext())
	// // {
	// // Element taskElement=(Element)iter.next();
	// //
	// //
	// // }
	// }
	// strResult.append(" 本次同步委外任务接收信息" + n + "条\n");
	// }
	//
	// n = 0;
	//
	// scheduleEventList = (List<ScheduleEvent>) scheduleEventDao
	// .getUnHandleEvents(scheme.getScheduleUid(),
	// ScheduleEvent.EVENTTYPE_REFUSE_COTASK, scheme
	// .getLastUpdateTime(), thisUpdateTime, null);
	// if (scheduleEventList != null && scheduleEventList.size() > 0) {
	// SimpleDateFormat formatDate = new SimpleDateFormat(
	// "yyyy-MM-dd HH:mm:ss");
	// for (ScheduleEvent scheduleEvent : scheduleEventList) {
	// try {
	// String strXml = scheduleEvent.getEventContent();
	// StringReader read = new StringReader(strXml);
	// Document doc = sb.build(read);
	//
	// Element rootElement = doc.getRootElement();
	// String taskUid = rootElement.getAttributeValue("taskUid");
	// SOperationTask co = scheme.getAllOperationTaskMap().get(
	// taskUid);
	//
	// co.setNotes(rootElement.getAttributeValue("notes"));
	// co.setCoTaskState(SOperationTask.COTASKSTATE_REFUSED);
	// strResult.append(" 委外任务被拒绝:" + co.toFriendlyString()
	// + "\n");
	//
	// scheduleEvent
	// .setEventState(ScheduleEvent.EVENTSTATE_SUCCESS);
	// n++;
	// } catch (RuntimeException e) {
	// scheduleEvent
	// .setEventState(ScheduleEvent.EVENTSTATE_FAILURE);
	// e.printStackTrace();
	// }
	//
	// scheduleEvent.setHandler(MMUtils.getSessionEmployeeId());
	// scheduleEvent.setHandleTime(new Date());
	//
	// // scheme.getProcessedEventList().add(scheduleEvent);
	//
	// // Iterator iter=rootElement.getChildren().iterator();
	// // while(iter.hasNext())
	// // {
	// // Element taskElement=(Element)iter.next();
	// //
	// //
	// // }
	// }
	// strResult.append(" 本次同步委外任务拒绝信息" + n + "条\n");
	// }
	//
	// return strResult.toString();
	// }

	//  
	// public String syncLateFinishChange(ScheduleScheme scheme,
	// Date thisUpdateTime) throws Exception {
	//
	// // TODO Auto-generated method stub
	// SAXBuilder sb = new SAXBuilder(false);
	// StringBuilder strResult = new StringBuilder();
	// strResult.append("开始同步交货期变更信息：\n");
	// int n = 0;
	//
	// List<ScheduleEvent> scheduleEventList = (List<ScheduleEvent>)
	// scheduleEventDao
	// .getUnHandleEvents(scheme.getScheduleUid(),
	// ScheduleEvent.EVENTTYPE_LATEFINISHCHANGE, scheme
	// .getLastUpdateTime(), thisUpdateTime, null);
	// if (scheduleEventList != null && scheduleEventList.size() > 0) {
	// SimpleDateFormat formatDate = new SimpleDateFormat(
	// "yyyy-MM-dd HH:mm:ss");
	// for (ScheduleEvent scheduleEvent : scheduleEventList) {
	// try {
	// String strXml = scheduleEvent.getEventContent();
	// StringReader read = new StringReader(strXml);
	// Document doc = sb.build(read);
	//
	// Element rootElement = doc.getRootElement();
	// String taskUid = rootElement.getAttributeValue("taskUid");
	// SPartTask partTask = scheme.getAllPartTaskMap()
	// .get(taskUid);
	// if (partTask != null
	// && rootElement.getAttributeValue("newDate") != null) {
	// String strDate = rootElement
	// .getAttributeValue("newDate");
	// Date dtLateFinish = formatDate.parse(strDate);
	// partTask.setLateFinish(dtLateFinish);
	// strResult.append(partTask + "交货期变为：" + strDate + "\n");
	// }
	// scheduleEvent
	// .setEventState(ScheduleEvent.EVENTSTATE_SUCCESS);
	// n++;
	// } catch (RuntimeException e) {
	// scheduleEvent
	// .setEventState(ScheduleEvent.EVENTSTATE_FAILURE);
	// e.printStackTrace();
	// }
	//
	// scheduleEvent.setHandler(MMUtils.getSessionEmployeeId());
	// scheduleEvent.setHandleTime(new Date());
	//
	// // scheme.getProcessedEventList().add(scheduleEvent);
	//
	// }
	// strResult.append("本次同步交货期变更信息" + n + "条\n");
	// }
	// return strResult.toString();
	// }

	private String eventProPublichCoTask(ScheduleScheme scheme,
			ScheduleEvent scheduleEvent, Document contentXml) {

		SimpleDateFormat formatDate = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");

		try {
			Element rootElement = contentXml.getRootElement();
			String taskUid = rootElement.getAttributeValue("taskUid");
			SCoTask co;
			String str;

			co = (SCoTask) scheme.getCoTaskMap().get(taskUid);
			if (co == null) {
				for (SOperationTask so : scheme.getCoTaskMap().values()) {
					if (so.getPartUid().equals(
							rootElement.getAttributeValue("partUid"))
							&& so.getBatchNum().equals(
									rootElement.getAttributeValue("batchNum"))
							&& so
									.getOperationIdDesc()
									.equals(
											rootElement
													.getAttributeValue("operationIdDesc"))) {
						co = (SCoTask) so;
						break;
					}

				}

			}

			if (co != null) {
				str = "    更新协作任务 ";
			} else {
				str = "    新增协作任务 ";
				co = new SCoTask();

				co.setTaskUid(taskUid);

				co.setTaskName(rootElement.getAttributeValue("taskName"));
				co.setPartUid(rootElement.getAttributeValue("partUid"));
				co.setDrawingId(rootElement.getAttributeValue("drawingId"));
				co.setPartName(rootElement.getAttributeValue("partName"));
				co.setBatchNum(rootElement.getAttributeValue("batchNum"));
				co.setOperationIdDesc(rootElement
						.getAttributeValue("operationIdDesc"));
				co.setDeviceClass(rootElement.getAttributeValue("deviceClass"));
				co.setDeviceClassName(rootElement
						.getAttributeValue("deviceClassName"));
				co.setDeptUid(rootElement.getAttributeValue("deptUid"));
				co.setDeptName(rootElement.getAttributeValue("deptName"));
				co.setMasterShop(rootElement.getAttributeValue("masterShop"));
				co.setMasterShopName(rootElement
						.getAttributeValue("masterShopName"));
				co.setOpUid(rootElement.getAttributeValue("opUid"));
				if (StringUtils.isNotEmpty(rootElement
						.getAttributeValue("planGrade")))
					co.setPlanGrade(Integer.valueOf(rootElement
							.getAttributeValue("planGrade")));
				if (StringUtils.isNotEmpty(rootElement
						.getAttributeValue("estiPreTime")))
					co.setEstiPreTime(Double.valueOf(rootElement
							.getAttributeValue("estiPreTime")));
				if (StringUtils.isNotEmpty(rootElement
						.getAttributeValue("estiRunTime")))
					co.setEstiRunTime(Double.valueOf(rootElement
							.getAttributeValue("estiRunTime")));
				if (StringUtils.isNotEmpty(rootElement
						.getAttributeValue("planQty")))
					co.setPlanQty(Double.valueOf(rootElement
							.getAttributeValue("planQty")));
				if (StringUtils.isNotEmpty(rootElement
						.getAttributeValue("completeQty")))
					co.setCompleteQty(Double.valueOf(rootElement
							.getAttributeValue("completeQty")));
				// 如果允许继承优先级与色带
				if (scheme.getInheritCoTaskPriority()) {
					if (StringUtils.isNotEmpty(rootElement
							.getAttributeValue("priority")))
						co.setPriority(Integer.valueOf(rootElement
								.getAttributeValue("priority")));

					if (StringUtils.isNotEmpty(rootElement
							.getAttributeValue("slackFactor")))
						co.setSlackFactor(Double.valueOf(rootElement
								.getAttributeValue("slackFactor")));

				}

				co = this.scheduleOperationTaskManager.addOperationTask(scheme,
						co);

			}
			// 如果允许继承优先级与色带
			if (scheme.getInheritCoTaskPriority()) {
				if (StringUtils.isNotEmpty(rootElement
						.getAttributeValue("priority")))
					co.setPriority(Integer.valueOf(rootElement
							.getAttributeValue("priority")));

				if (StringUtils.isNotEmpty(rootElement
						.getAttributeValue("slackFactor")))
					co.setSlackFactor(Double.valueOf(rootElement
							.getAttributeValue("slackFactor")));

			}
			if (StringUtils.isNotEmpty(rootElement
					.getAttributeValue("earlyStart")))
				co.setEarlyStart(formatDate.parse(rootElement
						.getAttributeValue("earlyStart")));
			if (StringUtils.isNotEmpty(rootElement
					.getAttributeValue("lateFinish")))
				co.setLateFinish(formatDate.parse(rootElement
						.getAttributeValue("lateFinish")));
			co.setNotes(rootElement.getAttributeValue("notes"));
			// if(co.getNotes()!=null)
			// {
			// co.setNotes(co.getNotes()+"\n"+rootElement.getAttributeValue("notes"));
			// }
			// else {
			// co.setNotes(rootElement.getAttributeValue("notes"));
			// }
			this.scheduleOperationTaskManager.updateOperationTask(scheme, co);

			return str + co.toFriendlyString();
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	// ScheduleEvent.EVENTTYPE_UNPUBLISH_COTASK
	private String eventProUnPublichCoTask(ScheduleScheme scheme,
			ScheduleEvent scheduleEvent, Document contentXml) throws Exception {

		Element rootElement = contentXml.getRootElement();

		try {
			String taskUid = rootElement.getAttributeValue("taskUid");
			SCoTask co;
			if (scheme.getCoTaskMap().containsKey(taskUid)) {
				co = (SCoTask) scheme.getCoTaskMap().get(taskUid);
				// 同步对方的取消发布协作任务时，自己需要删除已经接收的任务
				this.scheduleOperationTaskManager.removeOperationTask(co, true);

				scheduleEvent.setEventState(ScheduleEvent.EVENTSTATE_SUCCESS);
				return ("    取消协作任务:" + co.toFriendlyString());

			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

	// ScheduleEvent.EVENTTYPE_FEEDBACK_COTASK
	private String eventProFeedbackCoTask(ScheduleScheme scheme,
			ScheduleEvent scheduleEvent, Document contentXml,
			Map<String, SOperationTask> OperationTaskMap) throws Exception {
		try {
			SimpleDateFormat formatDate = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");

			Element rootElement = contentXml.getRootElement();
			String taskUid = rootElement.getAttributeValue("taskUid");
			// SOperationTask co = scheme.getAllOperationTaskMap().get(taskUid);

			SOperationTask co = this.getScheduleTask(scheme, taskUid,
					OperationTaskMap);

			if (co != null
					&& rootElement.getAttributeValue("planStart") != null
					&& rootElement.getAttributeValue("planFinish") != null) {
				if (StringUtils.isNotEmpty(rootElement
						.getAttributeValue("planStart")))
					co.setPlanStart(formatDate.parse(rootElement
							.getAttributeValue("planStart")));
				if (StringUtils.isNotEmpty(rootElement
						.getAttributeValue("planFinish")))
					co.setPlanFinish(formatDate.parse(rootElement
							.getAttributeValue("planFinish")));
				co.setNotes(rootElement.getAttributeValue("notes"));
				co.setCoTaskState(SOperationTask.COTASKSTATE_FEEDBACKED);
				co.setLocked(1); // 协作任务自动设置为锁定
				return ("    委外任务反馈信息（锁定）:" + co.toFriendlyString());
			}
			// added by hba for judging if needing loecked
			if (co != null
					&& rootElement.getAttributeValue("earlyStart") != null) {
				if (StringUtils.isNotEmpty(rootElement
						.getAttributeValue("earlyStart")))
					co.setEarlyStart(formatDate.parse(rootElement
							.getAttributeValue("earlyStart")));
				co.setNotes(rootElement.getAttributeValue("notes"));
				co.setCoTaskState(SOperationTask.COTASKSTATE_FEEDBACKED);
				co.setLocked(0); // 开始和结束时间之外的任务不锁定
				return ("    委外任务反馈信息（不锁定）:" + co.toFriendlyString());
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;

	}

	// 锁定工序任务
	private String eventProLockTask(ScheduleScheme scheme,
			ScheduleEvent scheduleEvent, Document contentXml,
			Map<String, SOperationTask> OperationTaskMap) throws Exception {
		SimpleDateFormat formatDate = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");

		try {
			Element rootElement = contentXml.getRootElement();
			String taskUid = rootElement.getAttributeValue("taskUid");
			// SOperationTask co = scheme.getAllOperationTaskMap().get(taskUid);

			SOperationTask co = this.getScheduleTask(scheme, taskUid,
					OperationTaskMap);

			if (co != null
					&& rootElement.getAttributeValue("planStart") != null
					&& rootElement.getAttributeValue("planFinish") != null) {
				co.setPlanStart(formatDate.parse(rootElement
						.getAttributeValue("planStart")));
				co.setPlanFinish(formatDate.parse(rootElement
						.getAttributeValue("planFinish")));
				co.setNotes(rootElement.getAttributeValue("notes"));
				co.setLocked(1); // 协作任务自动设置为锁定
				return ("    工序任务锁定信息:" + co.toFriendlyString());
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;

	}

	// ScheduleEvent.EVENTTYPE_RECEIVE_COTASK
	private String eventProReceiveCoTask(ScheduleScheme scheme,
			ScheduleEvent scheduleEvent, Document contentXml,
			Map<String, SOperationTask> OperationTaskMap) throws Exception {
		SimpleDateFormat formatDate = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");

		try {
			Element rootElement = contentXml.getRootElement();
			String taskUid = rootElement.getAttributeValue("taskUid");

			// SOperationTask co = scheme.getAllOperationTaskMap().get(taskUid);

			SOperationTask co = this.getScheduleTask(scheme, taskUid,
					OperationTaskMap);

			if (co != null) {
				co.setNotes(rootElement.getAttributeValue("notes"));
				co.setCoTaskState(SOperationTask.COTASKSTATE_RECEIVED);
				return ("    委外任务已接收:" + co.toFriendlyString());
			}
		} catch (RuntimeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;

	}

	// ScheduleEvent.EVENTTYPE_REFUSE_COTASK
	private String eventProRefuseCoTask(ScheduleScheme scheme,
			ScheduleEvent scheduleEvent, Document contentXml,
			Map<String, SOperationTask> OperationTaskMap) throws Exception {

		try {
			Element rootElement = contentXml.getRootElement();
			String taskUid = rootElement.getAttributeValue("taskUid");
			// SOperationTask co = scheme.getAllOperationTaskMap().get(taskUid);

			SOperationTask co = this.getScheduleTask(scheme, taskUid,
					OperationTaskMap);

			if (co != null) {
				co.setNotes(rootElement.getAttributeValue("notes"));
				co.setCoTaskState(SOperationTask.COTASKSTATE_REFUSED);
				return ("    委外任务被拒绝:" + co.toFriendlyString());
			}
		} catch (RuntimeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

	// ScheduleEvent.EVENTTYPE_LATEFINISHCHANGE
	private String eventProLateFinishChange(ScheduleScheme scheme,
			ScheduleEvent scheduleEvent, Document contentXml) {

		SimpleDateFormat formatDate = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String str = "";
		try {
			Element rootElement = contentXml.getRootElement();
			String taskUid = rootElement.getAttributeValue("taskUid");
			SPartTask partTask = scheme.getAllPartTaskMap().get(taskUid);
			if (partTask != null
					&& rootElement.getAttributeValue("newDate") != null
					&& rootElement.getAttributeValue("newDate") != "") {
				String strDate = rootElement.getAttributeValue("newDate");
				Date dtLateFinish = formatDate.parse(strDate);
				partTask.setLateFinish(dtLateFinish);
				str = (partTask + "交货期变为：" + strDate);
			} else if (partTask != null
					&& (rootElement.getAttributeValue("newDate") == null || rootElement
							.getAttributeValue("newDate") == "")) {
				partTask.setLateFinish(null);
				str = (partTask + "交货期取消");
			}
			;

			// 如果本批零件已经合批
			SPartTask scp = this.schedulePartTaskManager
					.getCombineBatch(partTask);
			if (scp != null) {
				this.schedulePartTaskManager.refreshCombineBatch(scp);
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return str;

	}

	// ScheduleEvent.EVENTTYPE_DISPATCH_TASK
	private String eventProDispatchTask(ScheduleScheme scheme,
			ScheduleEvent scheduleEvent, Document contentXml,
			Map<String, SOperationTask> OperationTaskMap) throws Exception {
		try {
			SimpleDateFormat formatDate = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");

			Element rootElement = contentXml.getRootElement();
			String taskUid = rootElement.getAttributeValue("taskUid");
			// SOperationTask co = scheme.getAllOperationTaskMap().get(taskUid);

			SOperationTask operationTask = this.getScheduleTask(scheme,
					taskUid, OperationTaskMap);

			if (operationTask != null) {
				String deviceUid = rootElement.getAttributeValue("deviceUid");
				SDevice device = scheme.getDeviceMap().get(deviceUid);

				if (device != null) {
					operationTask.setDeviceUid(deviceUid);
					operationTask.setDevice(device);
				}
				// 不是很严格的状态控制
				// lqm todo
				if (operationTask.getTaskState() <= OperationTask.TASKSTATE_READY) {
					operationTask
							.setTaskState(SOperationTask.TASKSTATE_DISPATCHED);
					try {
						this.scheduleOperationTaskManager.update(operationTask);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}

				return (" 工人自领取:" + operationTask.toFriendlyString() + ",设备：" + device
						.getDeviceName());
			}
		} catch (RuntimeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

	// ScheduleEvent.EVENTTYPE_LATEFINISHCHANGE
	private String eventProPartTaskPlanInfoChange(ScheduleScheme scheme,
			ScheduleEvent scheduleEvent, Document contentXml) {

		SimpleDateFormat formatDate = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String str = null;
		try {
			Element rootElement = contentXml.getRootElement();
			String taskUid = rootElement.getAttributeValue("taskUid");
			// lqm todo
			// 对零件任务删除应该另组事件处理
			PartTask originPartTask = this.partTaskDao.getById(taskUid);
			if (originPartTask == null)
				return str;

			SPartTask partTask = this.schedulePartTaskManager
					.getSchedulePartTask(scheme, originPartTask);

			if (partTask != null) {
				str = partTask.toFriendlyString();
				if (originPartTask.getTaskState() == PartTask.TASKSTATE_COMPLETED) {
					this.schedulePartTaskManager
							.removePartTask(partTask, false);
					str += " 零组件任务完成";
					return str;
				}
				if (originPartTask.getTaskState() == PartTask.TASKSTATE_CANCELED) {
					this.schedulePartTaskManager.removePartTask(partTask, true);
					str += " 零组件任务取消";
					return str;
				}
				if (rootElement.getAttributeValue("lateFinish") != null
						&& rootElement.getAttributeValue("lateFinish") != "") {
					String strDate = rootElement
							.getAttributeValue("lateFinish");
					Date dtLateFinish = formatDate.parse(strDate);
					// if(dtLateFinish.equals(partTask.getLateFinish()))
					partTask.setLateFinish(dtLateFinish);
					str += ",交货期变为：" + strDate;
				} else if ((rootElement.getAttributeValue("lateFinish") == null || rootElement
						.getAttributeValue("lateFinish") == "")) {
					if (partTask.getLateFinish() != null) {
						partTask.setLateFinish(null);
						str += ",交货期取消";
					}
				}
				partTask.setIsCritical(Integer.parseInt(rootElement
						.getAttributeValue("isCritical")));

				// 直接跳过了mes中的数据
				if (!partTask.getPlanQty().equals(originPartTask.getPlanQty())) {
					this.schedulePartTaskManager
							.changePartTaskQty(scheme, partTask, originPartTask
									.getPlanQty().doubleValue());
					str += ",计划数更新为：" + originPartTask.getPlanQty();
				}

				// 如果本批零件已经合批
				SPartTask scp = this.schedulePartTaskManager
						.getCombineBatch(partTask);
				if (scp != null) {
					this.schedulePartTaskManager.refreshCombineBatch(scp);
				}

			}
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return str;

	}

	// ScheduleEvent.EVENTTYPE_SCHEDULECURRENTTIMECHANGE
	private String eventProScheduleCurrentTimeChange(ScheduleScheme scheme,
			ScheduleEvent scheduleEvent, Document contentXml) {

		SimpleDateFormat formatDate = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		Element rootElement = contentXml.getRootElement();
		String strDate = rootElement.getText();
		Date dt;
		try {
			dt = formatDate.parse(strDate);
			this.scheduleManager.setScheduleCurrentTime(scheme, dt);
			return "调度当前时间变为：" + strDate;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

	@Transactional
	 
	/*
	 * 最应该考虑用多线程处理的地方
	 */
	public String syncScheduleEvents(ScheduleScheme scheme,
			Map<String, SOperationTask> OperationTaskMap) throws Exception {

		SAXBuilder sb = new SAXBuilder(false);
		StringBuilder strResult = new StringBuilder();
		strResult.append("开始同步调度事件：\n");
		int n = 0;

		// List<ScheduleEvent> scheduleEventList = (List<ScheduleEvent>)
		// scheduleEventDao
		// .getUnHandleEvents(scheme.getScheduleUid(), scheme
		// .getLastUpdateTime(), thisUpdateTime, null);
		List<ScheduleEvent> scheduleEventList = (List<ScheduleEvent>) scheduleEventDao
				.getUnHandleEvents(scheme.getScheduleUid(), null);
		if (scheduleEventList != null && scheduleEventList.size() > 0) {
			String str = null;
			for (ScheduleEvent scheduleEvent : scheduleEventList) {
				try {

					String strXml = scheduleEvent.getEventContent();
					StringReader read = new StringReader(strXml);
					Document doc = sb.build(read);
					String eventType = scheduleEvent.getEventType();
					if (eventType
							.equals(ScheduleEvent.EVENTTYPE_PUBLISH_COTASK))
						str = this.eventProPublichCoTask(scheme, scheduleEvent,
								doc);
					else if (eventType
							.equals(ScheduleEvent.EVENTTYPE_UNPUBLISH_COTASK))
						str = this.eventProUnPublichCoTask(scheme,
								scheduleEvent, doc);
					else if (eventType
							.equals(ScheduleEvent.EVENTTYPE_RECEIVE_COTASK))
						str = this.eventProReceiveCoTask(scheme, scheduleEvent,
								doc, OperationTaskMap);
					else if (eventType
							.equals(ScheduleEvent.EVENTTYPE_FEEDBACK_COTASK))
						str = this.eventProFeedbackCoTask(scheme,
								scheduleEvent, doc, OperationTaskMap);
					else if (eventType
							.equals(ScheduleEvent.EVENTTYPE_LOCK_TASK))
						str = this.eventProLockTask(scheme, scheduleEvent, doc,
								OperationTaskMap);
					else if (eventType
							.equals(ScheduleEvent.EVENTTYPE_REFUSE_COTASK))
						str = this.eventProRefuseCoTask(scheme, scheduleEvent,
								doc, OperationTaskMap);
					else if (eventType
							.equals(ScheduleEvent.EVENTTYPE_LATEFINISHCHANGE))
						str = this.eventProLateFinishChange(scheme,
								scheduleEvent, doc);
					else if (eventType
							.equals(ScheduleEvent.EVENTTYPE_PARTTASK_PLANINFO))
						str = this.eventProPartTaskPlanInfoChange(scheme,
								scheduleEvent, doc);
					else if (eventType
							.equals(ScheduleEvent.EVENTTYPE_SCHEDULECURRENTTIMECHANGE))
						str = this.eventProScheduleCurrentTimeChange(scheme,
								scheduleEvent, doc);
					else if (eventType
							.equals(ScheduleEvent.EVENTTYPE_PREPARETASK_START))
						str = this.eventProStartPrepare(scheme, scheduleEvent,
								doc);
					else if (eventType
							.equals(ScheduleEvent.EVENTTYPE_PREPARETASK_FINISH))
						str = this.eventProCompletePrepare(scheme,
								scheduleEvent, doc);
					else if (eventType
							.equals(ScheduleEvent.EVENTTYPE_PREPARETASK_EXCEPTION))
						str = this.eventProExceptionPrepare(scheme,
								scheduleEvent, doc, OperationTaskMap);
					else if (eventType
							.equals(ScheduleEvent.EVENTTYPE_DEVICE_BEGINMAINT))
						str = this.eventProScheduleBeginMaint(scheme,
								scheduleEvent, doc);
					else if (eventType
							.equals(ScheduleEvent.EVENTTYPE_DEVICE_RESUMEMAINT))
						str = this.eventProScheduleResumeMaint(scheme,
								scheduleEvent, doc);
					else if (eventType
							.equals(ScheduleEvent.EVENTTYPE_DISPATCH_TASK))
						str = this.eventProDispatchTask(scheme, scheduleEvent,
								doc, OperationTaskMap);
					else if (eventType
							.equals(ScheduleEvent.EVENTTYPE_ADD_FEEDBACK))
						str = this.eventAddFeedback(scheme, scheduleEvent, doc,
								OperationTaskMap);
					if (str != null)
						strResult.append(str + "\n");
					scheduleEvent
							.setEventState(ScheduleEvent.EVENTSTATE_SUCCESS);
					n++;
				} catch (Exception e) {
					scheduleEvent
							.setEventState(ScheduleEvent.EVENTSTATE_FAILURE);
					log.error("事件错误编号为：" + scheduleEvent.getUuid(), e);
				}

//				scheduleEvent.setHandler1(SysUtil.getSessionEmployeeId());
				scheduleEvent.setHandleTime(new Date());
				// this.scheduleEventManager.update(scheduleEvent);

				// scheme.getProcessedEventList().add(scheduleEvent);

			}
			strResult.append("本次同步共处理调度事件" + n + "条\n");
		}
		return strResult.toString();
	}

	// ScheduleEvent.EVENTTYPE_RECEIVE_COTASK
	private String eventProStartPrepare(ScheduleScheme scheme,
			ScheduleEvent scheduleEvent, Document contentXml) {
		SimpleDateFormat formatDate = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");

		try {
			Element rootElement = contentXml.getRootElement();
			String taskUid = rootElement.getAttributeValue("taskUid");

			SOperationTask operationTask = scheme.getAllOperationTaskMap().get(
					taskUid);
			if (operationTask != null) {
				this.scheduleOperationTaskManager.startOfflinePrepare(scheme,
						operationTask, null);
				return ("    已开始生产准备:" + operationTask.toFriendlyString());
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;

	}

	// ScheduleEvent.EVENTTYPE_ADD_FEEDBACK
	private String eventAddFeedback(ScheduleScheme scheme,
			ScheduleEvent scheduleEvent, Document contentXml,
			Map<String, SOperationTask> OperationTaskKeyMap) {
		try {

			Element rootElement = contentXml.getRootElement();
			String taskUid = rootElement.getAttributeValue("taskUid");
			Double competeQty = rootElement.getAttributeValue("completeQty") != null ? Double
					.parseDouble(rootElement.getAttributeValue("completeQty"))
					: 0;
			Integer taskState = Integer.parseInt(rootElement
					.getAttributeValue("taskState"));

			OperationTask oo = operationTaskDao.getById(taskUid);

			if (oo == null)
				return null;

			SOperationTask currentOperationTask = getScheduleTask(scheme, oo,
					OperationTaskKeyMap);

			if (currentOperationTask == null)
				return null;

			if (currentOperationTask.isGroupTask()) {
				if (oo.isFinished()
						&& this.isAllMemberFinish(currentOperationTask))
					this.scheduleOperationTaskManager.completeTask(scheme,
							currentOperationTask);
				else {
					// 必须以该工序结尾才计数
					if (currentOperationTask.getOperationIdDesc().endsWith(
							oo.getOperationIdDesc()))
						this.scheduleOperationTaskManager.feedbackQty(scheme,
								currentOperationTask, competeQty, null, null);
				}
			} else {
				// 采用这种方法保持与外面的参数一致
				if (oo.isFinished())
					this.scheduleOperationTaskManager.completeTask(scheme,
							currentOperationTask);
				else
					this.scheduleOperationTaskManager.feedbackQty(scheme,
							currentOperationTask, competeQty, null, null);
			}

			return ("    " + currentOperationTask.toFriendlyString() + " 完成数:" + competeQty);

		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;

	}

	private String eventProCompletePrepare(ScheduleScheme scheme,
			ScheduleEvent scheduleEvent, Document contentXml) {
		try {
			SimpleDateFormat formatDate = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");

			Element rootElement = contentXml.getRootElement();
			String taskUid = rootElement.getAttributeValue("taskUid");

			SOperationTask operationTask = scheme.getAllOperationTaskMap().get(
					taskUid);
			if (operationTask != null) {

				this.scheduleOperationTaskManager.completeOfflinePrepare(
						scheme, operationTask, null);
				// add by zhangjiae
				if (rootElement.getAttributeValue("actualFinish") != null) {
					Date actualFinish = formatDate.parse(rootElement
							.getAttributeValue("actualFinish"));
					operationTask.setEarlyStart(actualFinish);
				}
				return ("    已完成生产准备:" + operationTask.toFriendlyString());

			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;

	}

	private String eventProExceptionPrepare(ScheduleScheme scheme,
			ScheduleEvent scheduleEvent, Document contentXml,
			Map<String, SOperationTask> OperationTaskKeyMap) throws Exception {
		SimpleDateFormat formatDate = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");

		try {
			Element rootElement = contentXml.getRootElement();
			String taskUid = rootElement.getAttributeValue("taskUid");

			OperationTask oo = operationTaskDao.getById(taskUid);
			if (oo == null)
				return null;
			SOperationTask operationTask = getScheduleTask(scheme, oo,
					OperationTaskKeyMap);
			if (operationTask == null)
				operationTask = scheme.getAllOperationTaskMap().get(taskUid);

			if (operationTask != null) {

				try {
					if (rootElement.getAttributeValue("estimateFinish") != null) {
						Date estimateFinish = formatDate.parse(rootElement
								.getAttributeValue("estimateFinish"));
						operationTask.setEarlyStart(estimateFinish);
					}

					// if(operationTask.getEarlyStart()==null ||
					// estimateFinish.after(operationTask.getEarlyStart()))
					// add by zhangjiae

				} catch (RuntimeException e) {
					// TODO Auto-generated catch block
					log.warn("预计完成日期无效 " + scheduleEvent);
				}

				return ("    生产准备异常:" + operationTask.toFriendlyString());
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;

	}

	 
	public String addWorkRecord(ScheduleScheme scheme, Date thisUpdateTime,
			Map<String, SOperationTask> OperationTaskMap) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	 
	public String syncScheduleEvents(ScheduleScheme scheme,
			Date thisUpdateTime, Map<String, SOperationTask> OperationTaskMap)
			throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	// /**
	// * 产生相应的生产准备任务
	// * @param prepare_taskuid 生产准备任务唯一号
	// * @param prepare_tasktype 生产准备类型 301
	// * @param creator 创建者
	// * @param taskuid 此生产准备任务关联的生产任务唯一号
	// * @param resuid 派工设备号
	// * @param final_time 生产准备任务终止时间，就是最终必须下定结论的时间
	// * @return 生产准备任务添加是否成功
	// */
	// private boolean producePrepareTaskHeader(String prepare_taskuid, String
	// prepare_tasktype, String creator, String taskuid, String resuid,
	// Timestamp final_time)
	// {
	// boolean isOK = false;
	//		
	// try
	// {
	// DBHandler handler = new DBHandler();
	// Connection connection = handler.getConn();
	// PreparedStatement state = null;
	//			
	// //在T_prepare_task表中添加一条记录
	// String insertSQL = "insert into T_prepare_task(prepare_taskuid,
	// prepare_tasktype, prepare_taskstate, creator, createtime, taskuid,
	// resuid, final_time)" +
	// " values(?, ?, ?, ?, ?, ?, ?, ?)";
	// state = connection.prepareStatement(insertSQL);
	// state.setString(1, prepare_taskuid);
	// state.setString(2, prepare_tasktype);
	// //205的意思就是待派工
	// state.setString(3, "205");
	// state.setString(4, creator);
	//			
	// Date date = new Date();
	// Timestamp stamp = new Timestamp(date.getTime());
	// state.setTimestamp(5, stamp);
	//			
	// state.setString(6, taskuid);
	// state.setString(7, resuid);
	// state.setTimestamp(8, final_time);
	// state.executeUpdate();
	//			
	// state.close();
	// connection.close();
	// handler.close();
	//			
	// isOK= true;
	// }
	// catch (SQLException e)
	// {
	// e.printStackTrace();
	// }
	// catch (NamingException e)
	// {
	// e.printStackTrace();
	// }
	//		
	// return isOK;
	// }

	 
	public void applyOperationToScheme(
			List<ScheduleOperationRecord> recordList, ScheduleScheme scheme)
			throws Exception {
		// TODO Auto-generated method stub
		if (recordList == null || scheme == null) {
			return;
		}
		Collections.sort(recordList, new Comparator<ScheduleOperationRecord>() {
			 
			public int compare(ScheduleOperationRecord o1,
					ScheduleOperationRecord o2) {
				// TODO Auto-generated method stub
				if (o1.getCreateTime().before(o2.getCreateTime())) {
					return -1;
				} else {
					return 1;
				}
			}
		});

		// 初始化partUid,batchNum,operationIddesc集合
		Map<String, SPartTask> allPartTaskMap = this.initPartTaskMap(scheme);
		Map<String, SOperationTask> allOperationTaskMap = this
				.initOperationTaskMap(scheme);

		SAXBuilder sb = new SAXBuilder(false);

		CopyOnWriteArrayList<ScheduleOperationRecord> readyRecordList = new CopyOnWriteArrayList<ScheduleOperationRecord>();
		for (ScheduleOperationRecord record : recordList) {

			if (record.getParentUid() == null) {
				readyRecordList.add(record);
			}
		}
		// if (readyRecordList != null && readyRecordList.size() > 0) {
		// Collections.sort(readyRecordList,
		// new Comparator<ScheduleOperationRecord>() {
		//  
		// public int compare(ScheduleOperationRecord o1,
		// ScheduleOperationRecord o2) {
		// // TODO Auto-generated method stub
		// if (o1.getCreateTime().before(o2.getCreateTime())) {
		// return -1;
		// } else {
		// return 1;
		// }
		// }
		// });
		// }

		// 这个地方改成while可能比较好，直到就绪操作集合变为空
		int index = 0;
		while (readyRecordList != null && readyRecordList.size() > 0) {
			allPartTaskMap = this.initPartTaskMap(scheme);
			allOperationTaskMap = this.initOperationTaskMap(scheme);
			ScheduleOperationRecord record = readyRecordList.get(index);
			// 暂时只支持未生效的操作执行
			if (record.getEventState() >= 2) {
				readyRecordList.remove(record);
				continue;
			}
			try {

				// 如果存在子操作记录，则递归调用
				// if (childRecordsList.size() > 0) {
				// applyOperationToScheme(childRecordsList, scheme);
				// }

				SimpleDateFormat formatDate = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				BeanUtils beanUtils = new BeanUtils();
				Element element = this.scheduleOperationRecordManager
						.createElementFormat(record, allPartTaskMap,
								allOperationTaskMap);
				// StringReader read = new StringReader(strXml);
				// Document doc = sb.build(read);
				String eventType = record.getEventType();

				// 工序任务计划信息——调用工序任务的保存功能
				if (eventType
						.equals(ScheduleEvent.EVENTTYPE_OPERATIONTASK_PLANINFO)) {
					// 按照正向执行
					operationTaskPlanInfo(scheme, element, allOperationTaskMap,
							formatDate, 1, false);
				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_PARTTASK_COMBINEBATCH)) {
					partTaskComnineBatch(scheme, element, allPartTaskMap,
							formatDate, false);
				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_PARTTASK_CANCELCOMBINEBATCH)) {
					partTaskCancelCombineBatch(scheme, element, allPartTaskMap,
							formatDate, false);
				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_PARTTASK_SPLITBATCH)) {
					partTaskSplitBatch(scheme, element, allPartTaskMap,
							formatDate, false);
				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_PARTTASK_CANCELSPLITBATCH)) {
					partTaskCancelSplitBatch(scheme, element, allPartTaskMap,
							formatDate, false);
				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_PARTTASK_PLANINFO)) {
					partTaskPlanInfo(scheme, element, allPartTaskMap,
							formatDate, 1, false);
				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_OPERATIONTASK_GROUP)) {
					operatinoTaskGroup(scheme, element, allOperationTaskMap,
							formatDate);
				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_OPERATIONTASK_CANCELGROUP)) {
					operationTaskCancenGroup(scheme, element,
							allOperationTaskMap, formatDate);
				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_PARTTASK_ADD)) {
					partTaskAdd(scheme, element, allPartTaskMap, formatDate);
				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_PARTTASK_DELETE)) {
					partTaskDelete(scheme, element, allPartTaskMap, formatDate);
				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_OPERATIONTASK_ADD)) {
					operationTaskAdd(scheme, element, allOperationTaskMap,
							allPartTaskMap, formatDate);
				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_OPERATIONTASK_DELETE)) {
					operationTaskDelete(scheme, element, allOperationTaskMap,
							allPartTaskMap, formatDate);
				}
				List<ScheduleOperationRecord> childRecordsList = this.scheduleOperationRecordDao
						.findChildRecord(record);
				// 运行成功设为已生效状态
				record.setEventState(2);
				this.scheduleOperationRecordManager.update(record);
				readyRecordList.remove(record);
				// 如果有子操作
				if (childRecordsList != null && childRecordsList.size() > 0) {
					// 子操作进行时间排序
					Collections.sort(childRecordsList,
							new Comparator<ScheduleOperationRecord>() {
								 
								public int compare(ScheduleOperationRecord o1,
										ScheduleOperationRecord o2) {
									if (o1.getCreateTime().after(
											o2.getCreateTime())) {
										return 1;
									}
									if (o1.getCreateTime().before(
											o2.getCreateTime())) {
										return -1;
									}
									// TODO Auto-generated method stub
									return 0;
								}
							});
					// 加入之前要判断是不是勾选的，是才能加入就绪集合
					for (ScheduleOperationRecord existedOpRecord : childRecordsList) {
						if (recordList.contains(existedOpRecord)) {
							readyRecordList.add(existedOpRecord);
						}
					}

				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				// 运行失败耳朵话暂时设为失效状态
				record.setEventState(3);
				this.scheduleOperationRecordManager.update(record);
				readyRecordList.remove(record);
				e.printStackTrace();
			}
		}
	}

	 
	public void applyEventToScheme(List<ScheduleEvent> eventList,
			ScheduleScheme scheme) throws ParseException {
		// TODO Auto-generated method stub
		if (eventList == null || scheme == null) {
			return;
		}
		Collections.sort(eventList, new Comparator<ScheduleEvent>() {
			 
			public int compare(ScheduleEvent o1, ScheduleEvent o2) {
				// TODO Auto-generated method stub
				if (o1.getCreateTime().before(o2.getCreateTime())) {
					return -1;
				} else {
					return 1;
				}
			}
		});

		// 初始化partUid,batchNum,operationIddesc集合
		Map<String, SPartTask> allPartTaskMap = this.initPartTaskMap(scheme);
		Map<String, SOperationTask> allOperationTaskMap = this
				.initOperationTaskMap(scheme);

		SAXBuilder sb = new SAXBuilder(false);
		for (ScheduleEvent scheduleEvent : eventList) {
			try {
				SimpleDateFormat formatDate = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				BeanUtils beanUtils = new BeanUtils();
				String strXml = scheduleEvent.getEventContent();
				StringReader read = new StringReader(strXml);
				Document doc = sb.build(read);
				String eventType = scheduleEvent.getEventType();

				// 工序任务计划信息——调用工序任务的保存功能
				if (eventType
						.equals(ScheduleEvent.EVENTTYPE_OPERATIONTASK_PLANINFO)) {
					// 按照正向执行
					operationTaskPlanInfo(scheme, doc, allOperationTaskMap,
							formatDate, 1, true);
				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_PARTTASK_COMBINEBATCH)) {
					partTaskComnineBatch(scheme, doc, allPartTaskMap,
							formatDate, true);
				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_PARTTASK_CANCELCOMBINEBATCH)) {
					partTaskCancelCombineBatch(scheme, doc, allPartTaskMap,
							formatDate, true);
				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_PARTTASK_SPLITBATCH)) {
					partTaskSplitBatch(scheme, doc, allPartTaskMap, formatDate,
							true);
				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_PARTTASK_CANCELSPLITBATCH)) {
					partTaskCancelSplitBatch(scheme, doc, allPartTaskMap,
							formatDate, true);
				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_PARTTASK_PLANINFO)) {
					partTaskPlanInfo(scheme, doc, allPartTaskMap, formatDate,
							1, true);
				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_OPERATIONTASK_GROUP)) {
					operatinoTaskGroup(scheme, doc, allOperationTaskMap,
							formatDate);
				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_OPERATIONTASK_CANCELGROUP)) {
					operationTaskCancenGroup(scheme, doc, allOperationTaskMap,
							formatDate);
				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_PARTTASK_ADD)) {
					partTaskAdd(scheme, doc, allPartTaskMap, formatDate);
				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_PARTTASK_DELETE)) {
					partTaskDelete(scheme, doc, allPartTaskMap, formatDate);
				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_OPERATIONTASK_ADD)) {
					operationTaskAdd(scheme, doc, allOperationTaskMap,
							allPartTaskMap, formatDate);
				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_OPERATIONTASK_DELETE)) {
					operationTaskDelete(scheme, doc, allOperationTaskMap,
							allPartTaskMap, formatDate);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	 
	public void reverseEvent(List<ScheduleEvent> eventList,
			ScheduleScheme scheme) throws Exception {

		// TODO Auto-generated method stub
		if (eventList == null || scheme == null) {
			return;
		}
		Collections.sort(eventList, new Comparator<ScheduleEvent>() {
			 
			public int compare(ScheduleEvent o1, ScheduleEvent o2) {
				// TODO Auto-generated method stub
				if (o1.getCreateTime().before(o2.getCreateTime())) {
					return -1;
				} else {
					return 1;
				}
			}
		});

		// 初始化partUid,batchNum,operationIddesc集合
		Map<String, SPartTask> allPartTaskMap = this.initPartTaskMap(scheme);
		Map<String, SOperationTask> allOperationTaskMap = this
				.initOperationTaskMap(scheme);

		SAXBuilder sb = new SAXBuilder(false);
		for (ScheduleEvent scheduleEvent : eventList) {
			try {
				SimpleDateFormat formatDate = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				BeanUtils beanUtils = new BeanUtils();
				String strXml = scheduleEvent.getEventContent();
				StringReader read = new StringReader(strXml);
				Document doc = sb.build(read);
				String eventType = scheduleEvent.getEventType();
				int eventState = scheduleEvent.getEventState();
				// 工序任务计划信息——调用工序任务的保存功能
				if (eventType
						.equals(ScheduleEvent.EVENTTYPE_OPERATIONTASK_PLANINFO)) {
					// 工序的修改信息返回的话需要记住以前的信息
					operationTaskPlanInfo(scheme, doc, allOperationTaskMap,
							formatDate, eventState, false);
					if (eventState == 1) {
						scheduleEvent.setEventState(2);
					} else if (eventState == 2) {
						scheduleEvent.setEventState(1);
					}
				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_PARTTASK_COMBINEBATCH)) {
					if (eventState == 1) {
						partTaskComnineBatch(scheme, doc, allPartTaskMap,
								formatDate, false);
						scheduleEvent.setEventState(2);
					} else if (eventState == 2) {
						partTaskCancelCombineBatch(scheme, doc, allPartTaskMap,
								formatDate, false);
						scheduleEvent.setEventState(1);
					}
				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_PARTTASK_CANCELCOMBINEBATCH)) {
					if (eventState == 1) {
						partTaskCancelCombineBatch(scheme, doc, allPartTaskMap,
								formatDate, false);
						scheduleEvent.setEventState(2);

					} else if (eventState == 2) {
						partTaskComnineBatch(scheme, doc, allPartTaskMap,
								formatDate, false);
						scheduleEvent.setEventState(1);
					}
				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_PARTTASK_SPLITBATCH)) {
					if (eventState == 1) {
						partTaskSplitBatch(scheme, doc, allPartTaskMap,
								formatDate, false);
						scheduleEvent.setEventState(2);
					} else if (eventState == 2) {
						partTaskCancelSplitBatch(scheme, doc, allPartTaskMap,
								formatDate, false);
						scheduleEvent.setEventState(1);
					}

				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_PARTTASK_CANCELSPLITBATCH)) {
					if (eventState == 1) {
						partTaskCancelSplitBatch(scheme, doc, allPartTaskMap,
								formatDate, false);
						scheduleEvent.setEventState(2);
					} else if (eventState == 2) {
						partTaskSplitBatch(scheme, doc, allPartTaskMap,
								formatDate, false);
						scheduleEvent.setEventState(1);
					}

				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_PARTTASK_PLANINFO)) {

					// 零件的修改信息返回的话需要记住以前的信息
					partTaskPlanInfo(scheme, doc, allPartTaskMap, formatDate,
							eventState, false);
					if (eventState == 1) {
						scheduleEvent.setEventState(2);
					} else if (eventState == 2) {
						scheduleEvent.setEventState(1);
					}

				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_OPERATIONTASK_GROUP)) {
					if (eventState == 1) {
						operatinoTaskGroup(scheme, doc, allOperationTaskMap,
								formatDate);
						scheduleEvent.setEventState(2);
					} else if (eventState == 2) {
						operationTaskCancenGroup(scheme, doc,
								allOperationTaskMap, formatDate);
						scheduleEvent.setEventState(1);
					}
				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_OPERATIONTASK_CANCELGROUP)) {
					if (eventState == 1) {
						operationTaskCancenGroup(scheme, doc,
								allOperationTaskMap, formatDate);
						scheduleEvent.setEventState(2);
					} else if (eventState == 2) {
						operatinoTaskGroup(scheme, doc, allOperationTaskMap,
								formatDate);
						scheduleEvent.setEventState(1);
					}
				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_PARTTASK_ADD)) {
					if (eventState == 1) {
						partTaskAdd(scheme, doc, allPartTaskMap, formatDate);
						scheduleEvent.setEventState(2);
					} else if (eventState == 2) {
						partTaskDelete(scheme, doc, allPartTaskMap, formatDate);
						scheduleEvent.setEventState(1);
					}

				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_PARTTASK_DELETE)) {
					if (eventState == 1) {
						partTaskDelete(scheme, doc, allPartTaskMap, formatDate);
						scheduleEvent.setEventState(2);

					} else if (eventState == 2) {
						partTaskAdd(scheme, doc, allPartTaskMap, formatDate);
						scheduleEvent.setEventState(1);
					}

				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_OPERATIONTASK_ADD)) {
					if (eventState == 1) {
						operationTaskAdd(scheme, doc, allOperationTaskMap,
								allPartTaskMap, formatDate);
						scheduleEvent.setEventState(2);
					} else if (eventState == 2) {
						operationTaskDelete(scheme, doc, allOperationTaskMap,
								allPartTaskMap, formatDate);
						scheduleEvent.setEventState(1);
					}

				} else if (eventType
						.equals(ScheduleEvent.EVENTTYPE_OPERATIONTASK_DELETE)) {
					if (eventState == 1) {
						operationTaskDelete(scheme, doc, allOperationTaskMap,
								allPartTaskMap, formatDate);
						scheduleEvent.setEventState(2);
					} else if (eventState == 2) {
						operationTaskAdd(scheme, doc, allOperationTaskMap,
								allPartTaskMap, formatDate);
						scheduleEvent.setEventState(1);
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				// 放在这可能不合适
				this.scheduleEventManager.update(scheduleEvent);
			}
		}

	}

	private void operationTaskDelete(ScheduleScheme scheme, Document doc,
			Map<String, SOperationTask> allOperationTaskMap,
			Map<String, SPartTask> allPartTaskMap, SimpleDateFormat formatDate)
			throws Exception {

		Element rootElement = doc.getRootElement();
		String partUid = rootElement.getAttributeValue("partUid");
		String batchNum = rootElement.getAttributeValue("batchNum");
		String operationIdDesc = rootElement
				.getAttributeValue("operationIdDesc");
		String strKey = partUid + "_" + batchNum + "_" + operationIdDesc;
		String partStrKey = partUid + "_" + batchNum;
		SOperationTask opTask = allOperationTaskMap.get(strKey);
		SPartTask partTask = allPartTaskMap.get(partStrKey);
		if (opTask == null) {
			return;
		} else {
			List<SOperationTask> opTaskList = new ArrayList<SOperationTask>();
			opTask.setObjectState(BasicModel.OBJECTSTATE_TOBEDELETED);
			opTaskList.add(opTask);
			scheduleOperationTaskManager.saveOperationTask(scheme, partTask
					.getTaskUid(), opTaskList, true);
			this.scheduleOperationTaskManager.removeOperationTask(scheme,
					opTask.getTaskUid());
		}

	}

	private void operationTaskDelete(ScheduleScheme scheme,
			Element rootElement,
			Map<String, SOperationTask> allOperationTaskMap,
			Map<String, SPartTask> allPartTaskMap, SimpleDateFormat formatDate)
			throws Exception {

		// Element rootElement = doc.getRootElement();
		SOperationTask newOpTask = new SOperationTask();
		newOpTask.setObjectState(BasicModel.OBJECTSTATE_TOBEADDED);
		List<Element> elementList = rootElement.getChildren();
		for (Element element : elementList) {
			String drawingId = element.getAttributeValue("drawingId");
			String batchNum = element.getAttributeValue("batchNum");
			String operationIdDesc = element
					.getAttributeValue("operationIdDesc");
			String strKey = drawingId + "_" + batchNum + "_" + operationIdDesc;
			String partStrKey = drawingId + "_" + batchNum;
			SOperationTask opTask = allOperationTaskMap.get(strKey);
			SPartTask partTask = allPartTaskMap.get(partStrKey);
			if (opTask == null) {
				return;
			} else {
				List<SOperationTask> opTaskList = new ArrayList<SOperationTask>();
				opTask.setObjectState(BasicModel.OBJECTSTATE_TOBEDELETED);
				opTaskList.add(opTask);
				scheduleOperationTaskManager.saveOperationTask(scheme, partTask
						.getTaskUid(), opTaskList, true);
				this.scheduleOperationTaskManager.removeOperationTask(scheme,
						opTask.getTaskUid());
			}
		}

	}

	private void operationTaskAdd(ScheduleScheme scheme, Document doc,
			Map<String, SOperationTask> allOperationTaskMap,
			Map<String, SPartTask> allPartTaskMap, SimpleDateFormat formatDate)
			throws Exception {

		Element rootElement = doc.getRootElement();
		SOperationTask newOpTask = new SOperationTask();
		newOpTask.setObjectState(BasicModel.OBJECTSTATE_TOBEADDED);
		String taskUid = rootElement.getAttributeValue("taskUid");

		String partUid = rootElement.getAttributeValue("partUid");
		String batchNum = rootElement.getAttributeValue("batchNum");
		String operationIdDesc = rootElement
				.getAttributeValue("operationIdDesc");
		String strKey = partUid + "_" + batchNum + "_" + operationIdDesc;

		String partStrKey = partUid + "_" + batchNum;

		String drawingId = rootElement.getAttributeValue("drawingId");
		String partName = rootElement.getAttributeValue("partName");
		String taskName = rootElement.getAttributeValue("taskName");
		Float operationId = 0.0f;
		if (!rootElement.getAttributeValue("operationId").equals("")) {
			operationId = Float.valueOf(rootElement
					.getAttributeValue("operationId"));
		}

		double planQty = Double.valueOf(rootElement
				.getAttributeValue("planQty"));
		double completeQty = Double.valueOf(rootElement
				.getAttributeValue("completeQty"));
		double estiRunTime = Double.valueOf(rootElement
				.getAttributeValue("estiRunTime"));
		double estiPreTime = Double.valueOf(rootElement
				.getAttributeValue("estiPreTime"));
		double estiDelayTime = Double.valueOf(rootElement
				.getAttributeValue("estiDelayTime"));
		String succOperationStr = rootElement
				.getAttributeValue("succOperationStr");
		String masterShop = rootElement.getAttributeValue("masterShop");
		String masterShopName = rootElement.getAttributeValue("masterShopName");
		String deviceClass = rootElement.getAttributeValue("deviceClass");
		String deviceClassName = rootElement
				.getAttributeValue("deviceClassName");
		Integer deviceSeq = null;
		if (!rootElement.getAttributeValue("deviceSeq").equals("")) {
			deviceSeq = Integer.valueOf(rootElement
					.getAttributeValue("deviceSeq"));
		}
		Integer locked = null;
		if (!rootElement.getAttributeValue("locked").equals("")) {
			locked = Integer.valueOf(rootElement.getAttributeValue("locked"));
		}
		newOpTask.setPartUid(partUid);
		newOpTask.setBatchNum(batchNum);
		newOpTask.setDrawingId(drawingId);
		newOpTask.setPartName(partName);
		newOpTask.setPlanQty(planQty);
		newOpTask.setCompleteQty(completeQty);
		newOpTask.setEstiRunTime(estiRunTime);
		newOpTask.setEstiPreTime(estiPreTime);
		newOpTask.setEstiDelayTime(estiDelayTime);
		newOpTask.setOperationId(operationId);
		newOpTask.setOperationIdDesc(operationIdDesc);
		newOpTask.setTaskName(taskName);
		newOpTask.setSuccOperationStr(succOperationStr);
		newOpTask.setMasterShop(masterShop);
		newOpTask.setMasterShopName(masterShopName);
		newOpTask.setDeviceClass(deviceClass);
		newOpTask.setDeviceClassName(deviceClassName);
		newOpTask.setDeviceSeq(deviceSeq);
		newOpTask.setLocked(locked);

		if (!"".equals(rootElement.getAttributeValue("earlyStart"))) {
			Date earlyStart = formatDate.parse(rootElement
					.getAttributeValue("earlyStart"));
			newOpTask.setEarlyStart(earlyStart);
		}

		if (!"".equals(rootElement.getAttributeValue("lateFinish"))) {
			Date lateFinish = formatDate.parse(rootElement
					.getAttributeValue("lateFinish"));
			newOpTask.setLateFinish(lateFinish);
		}

		SOperationTask opTask = allOperationTaskMap.get(strKey);
		SPartTask partTask = allPartTaskMap.get(partStrKey);
		if (opTask != null) {
			return;
		} else {
			List<SOperationTask> opTaskList = new ArrayList<SOperationTask>();
			opTaskList.add(newOpTask);
			// scheduleOperationTaskManager.saveOperationTask(scheme, partTask
			// .getTaskUid(), opTaskList, true);
			// addOperationTask(scheme, so, partTask);
			this.scheduleOperationTaskManager.addOperationTask(scheme,
					newOpTask, partTask);

			// 按照后置工序排列零件的工序顺序
			if (partTask.getOperationTaskList().size() > 0) {
				Collections.sort(partTask.getOperationTaskList(),
						new Comparator<SOperationTask>() {
							 
							public int compare(SOperationTask o1,
									SOperationTask o2) {
								if (o1.getOperationIdDesc().length() > o2
										.getOperationIdDesc().length()) {
									return 1;
								} else if (o1.getOperationIdDesc().length() < o2
										.getOperationIdDesc().length()) {
									return -1;
								} else if (o1.getOperationIdDesc().length() == o2
										.getOperationIdDesc().length()) {
									if (o1.getOperationIdDesc().compareTo(
											o2.getOperationIdDesc()) == 0) {
										return 0;
									} else if (o1.getOperationIdDesc()
											.compareTo(o2.getOperationIdDesc()) > 0) {
										return 1;
									} else if (o1.getOperationIdDesc()
											.compareTo(o2.getOperationIdDesc()) < 0) {
										return -1;
									}
								}
								return 0;
							}
						});
			}
			float operationIdIndex = 0;
			// opTask为新建的任务，并没有taskUid
			// SOperationTask so1 =
			// allOperationTaskMap.getscheme.getAllOperationTaskMap().get(
			// opTask.getTaskUid());
			for (SOperationTask so : partTask.getOperationTaskList()) {
				SOperationTask so1 = scheme.getAllOperationTaskMap().get(
						so.getTaskUid());
				if (so1 != null) {
					so.setOperationId(++operationIdIndex);
					so1.setSuccOperationStr(so.getSuccOperationStr());
				}
			}

			this.scheduleOperationTaskManager.updateScheduleLink(true, opTask,
					partTask);
		}
	}

	private void operationTaskAdd(ScheduleScheme scheme, Element rootElement,
			Map<String, SOperationTask> allOperationTaskMap,
			Map<String, SPartTask> allPartTaskMap, SimpleDateFormat formatDate)
			throws Exception {

		// Element rootElement = doc.getRootElement();
		SOperationTask newOpTask = new SOperationTask();
		newOpTask.setObjectState(BasicModel.OBJECTSTATE_TOBEADDED);
		List<Element> elementList = rootElement.getChildren();
		for (Element element : elementList) {
			// String taskUid = rootElement.getAttributeValue("taskUid");

			String drawingId = element.getAttributeValue("drawingId");
			String batchNum = element.getAttributeValue("batchNum");
			String operationIdDesc = element
					.getAttributeValue("operationIdDesc");
			String strKey = drawingId + "_" + batchNum + "_" + operationIdDesc;
			String partStrKey = drawingId + "_" + batchNum;
			String partName = element.getAttributeValue("partName");
			String taskName = element.getAttributeValue("taskName");
			Float operationId = 0.0f;
			if (!element.getAttributeValue("operationId").equals("")) {
				operationId = Float.valueOf(element
						.getAttributeValue("operationId"));
			}
			double planQty = Double.valueOf(element
					.getAttributeValue("planQty"));
			double completeQty = Double.valueOf(element
					.getAttributeValue("completeQty"));
			double estiRunTime = Double.valueOf(element
					.getAttributeValue("estiRunTime"));
			double estiPreTime = Double.valueOf(element
					.getAttributeValue("estiPreTime"));
			double estiDelayTime = Double.valueOf(element
					.getAttributeValue("estiDelayTime"));
			String succOperationStr = element
					.getAttributeValue("succOperationStr");
			String masterShop = element.getAttributeValue("masterShop");
			String masterShopName = element.getAttributeValue("masterShopName");
			String deviceClass = element.getAttributeValue("deviceClass");
			String deviceClassName = element
					.getAttributeValue("deviceClassName");
			Integer deviceSeq = null;
			if (!element.getAttributeValue("deviceSeq").equals("")) {
				deviceSeq = Integer.valueOf(element
						.getAttributeValue("deviceSeq"));
			}
			Integer locked = null;
			if (!element.getAttributeValue("locked").equals("")) {
				locked = Integer.valueOf(element.getAttributeValue("locked"));
			}
			// newOpTask.setPartUid(partUid);
			newOpTask.setBatchNum(batchNum);
			newOpTask.setDrawingId(drawingId);
			newOpTask.setPartName(partName);
			newOpTask.setPlanQty(planQty);
			newOpTask.setCompleteQty(completeQty);
			newOpTask.setEstiRunTime(estiRunTime);
			newOpTask.setEstiPreTime(estiPreTime);
			newOpTask.setEstiDelayTime(estiDelayTime);
			newOpTask.setOperationId(operationId);
			newOpTask.setOperationIdDesc(operationIdDesc);
			newOpTask.setTaskName(taskName);
			newOpTask.setSuccOperationStr(succOperationStr);
			newOpTask.setMasterShop(masterShop);
			newOpTask.setMasterShopName(masterShopName);
			newOpTask.setDeviceClass(deviceClass);
			newOpTask.setDeviceClassName(deviceClassName);
			newOpTask.setDeviceSeq(deviceSeq);
			newOpTask.setLocked(locked);

			if (!"".equals(element.getAttributeValue("earlyStart"))) {
				Date earlyStart = formatDate.parse(element
						.getAttributeValue("earlyStart"));
				newOpTask.setEarlyStart(earlyStart);
			}

			if (!"".equals(element.getAttributeValue("lateFinish"))) {
				Date lateFinish = formatDate.parse(element
						.getAttributeValue("lateFinish"));
				newOpTask.setLateFinish(lateFinish);
			}

			SOperationTask opTask = allOperationTaskMap.get(strKey);
			SPartTask partTask = allPartTaskMap.get(partStrKey);
			if (opTask != null) {
				return;
			} else {
				List<SOperationTask> opTaskList = new ArrayList<SOperationTask>();
				opTaskList.add(newOpTask);
				// scheduleOperationTaskManager.saveOperationTask(scheme,
				// partTask
				// .getTaskUid(), opTaskList, true);
				// addOperationTask(scheme, so, partTask);
				this.scheduleOperationTaskManager.addOperationTask(scheme,
						newOpTask, partTask);

				// 按照后置工序排列零件的工序顺序
				if (partTask.getOperationTaskList().size() > 0) {
					Collections.sort(partTask.getOperationTaskList(),
							new Comparator<SOperationTask>() {
								 
								public int compare(SOperationTask o1,
										SOperationTask o2) {
									if (o1.getOperationIdDesc().length() > o2
											.getOperationIdDesc().length()) {
										return 1;
									} else if (o1.getOperationIdDesc().length() < o2
											.getOperationIdDesc().length()) {
										return -1;
									} else if (o1.getOperationIdDesc().length() == o2
											.getOperationIdDesc().length()) {
										if (o1.getOperationIdDesc().compareTo(
												o2.getOperationIdDesc()) == 0) {
											return 0;
										} else if (o1
												.getOperationIdDesc()
												.compareTo(
														o2.getOperationIdDesc()) > 0) {
											return 1;
										} else if (o1
												.getOperationIdDesc()
												.compareTo(
														o2.getOperationIdDesc()) < 0) {
											return -1;
										}
									}
									return 0;
								}
							});
				}
				float operationIdIndex = 0;
				// opTask为新建的任务，并没有taskUid
				// SOperationTask so1 =
				// allOperationTaskMap.getscheme.getAllOperationTaskMap().get(
				// opTask.getTaskUid());
				for (SOperationTask so : partTask.getOperationTaskList()) {
					SOperationTask so1 = scheme.getAllOperationTaskMap().get(
							so.getTaskUid());
					if (so1 != null) {
						so.setOperationId(++operationIdIndex);
						so1.setSuccOperationStr(so.getSuccOperationStr());
					}
				}

				this.scheduleOperationTaskManager.updateScheduleLink(true,
						opTask, partTask);
			}
		}

	}

	private void partTaskDelete(ScheduleScheme scheme, Document doc,
			Map<String, SPartTask> allPartTaskMap, SimpleDateFormat formatDate)
			throws Exception {

		Element rootElement = doc.getRootElement();
		String partUid = rootElement.getAttributeValue("partUid");
		String batchNum = rootElement.getAttributeValue("batchNum");
		String strKey = partUid + "_" + batchNum;

		SPartTask partTask = allPartTaskMap.get(strKey);
		// 已经产出不做处理
		if (partTask == null) {
			return;
		} else {
			List<SPartTask> partTaskList = new ArrayList<SPartTask>();
			partTask.setObjectState(BasicModel.OBJECTSTATE_TOBEDELETED);
			partTaskList.add(partTask);
			schedulePartTaskManager.removePartTask(partTask, true);
		}
	}

	private void partTaskDelete(ScheduleScheme scheme, Element rootElement,
			Map<String, SPartTask> allPartTaskMap, SimpleDateFormat formatDate)
			throws Exception {

		// Element rootElement = doc.getRootElement();
		List<Element> elementList = rootElement.getChildren();
		for (Element element : elementList) {
			String partUid = element.getAttributeValue("drawingId");
			String batchNum = element.getAttributeValue("batchNum");
			String strKey = partUid + "_" + batchNum;

			SPartTask partTask = allPartTaskMap.get(strKey);
			// 已经产出不做处理
			if (partTask == null) {
				return;
			} else {
				List<SPartTask> partTaskList = new ArrayList<SPartTask>();
				partTask.setObjectState(BasicModel.OBJECTSTATE_TOBEDELETED);
				partTaskList.add(partTask);
				schedulePartTaskManager.removePartTask(partTask, true);
			}
		}

	}

	private void partTaskAdd(ScheduleScheme scheme, Document doc,
			Map<String, SPartTask> allPartTaskMap, SimpleDateFormat formatDate)
			throws Exception {

		Element rootElement = doc.getRootElement();
		SPartTask newPartTask = new SPartTask();
		newPartTask.setObjectState(BasicModel.OBJECTSTATE_TOBEADDED);
		// String taskUid =
		// rootElement.getAttributeValue("taskUid");

		String partUid = rootElement.getAttributeValue("partUid");
		String batchNum = rootElement.getAttributeValue("batchNum");
		String strKey = partUid + "_" + batchNum;
		String drawingId = rootElement.getAttributeValue("drawingId");
		String partName = rootElement.getAttributeValue("partName");
		String model = rootElement.getAttributeValue("model");

		double planQty = Double.valueOf(rootElement
				.getAttributeValue("planQty"));
		int isCritical = Integer.valueOf(rootElement
				.getAttributeValue("isCritical"));
		int delayCost = Integer.valueOf(rootElement
				.getAttributeValue("delayCost"));
		int planGrade = Integer.valueOf(rootElement
				.getAttributeValue("planGrade"));

		newPartTask.setPartUid(partUid);
		newPartTask.setBatchNum(batchNum);
		newPartTask.setDrawingId(drawingId);
		newPartTask.setPartName(partName);
		newPartTask.setPlanQty(planQty);
		newPartTask.setIsCritical(isCritical);
		newPartTask.setDelayCost(delayCost);
		newPartTask.setPlanGrade(planGrade);
		newPartTask.setModel(model);
		newPartTask.setScheme(scheme);

		if (!"".equals(rootElement.getAttributeValue("earlyStart"))) {
			Date earlyStart = formatDate.parse(rootElement
					.getAttributeValue("earlyStart"));
			newPartTask.setEarlyStart(earlyStart);
		}

		if (!"".equals(rootElement.getAttributeValue("lateFinish"))) {
			Date lateFinish = formatDate.parse(rootElement
					.getAttributeValue("lateFinish"));
			newPartTask.setLateFinish(lateFinish);
		}

		SPartTask partTask = allPartTaskMap.get(strKey);
		// 已经存在就不处理
		if (partTask != null) {
			return;
		} else {
			List<SPartTask> partTaskList = new ArrayList<SPartTask>();
			partTaskList.add(newPartTask);
			// 不要写事件
			schedulePartTaskManager.addPartTask(scheme, newPartTask);
		}
	}

	private void partTaskAdd(ScheduleScheme scheme, Element rootElement,
			Map<String, SPartTask> allPartTaskMap, SimpleDateFormat formatDate)
			throws Exception {

		// Element rootElement = doc.getRootElement();
		SPartTask newPartTask = new SPartTask();
		newPartTask.setObjectState(BasicModel.OBJECTSTATE_TOBEADDED);
		// String taskUid =
		// rootElement.getAttributeValue("taskUid");
		List<Element> elementList = rootElement.getChildren();
		for (Element element : elementList) {
			String partUid = element.getAttributeValue("partUid");
			String batchNum = element.getAttributeValue("batchNum");
			String strKey = partUid + "_" + batchNum;
			String drawingId = element.getAttributeValue("drawingId");
			String partName = element.getAttributeValue("partName");
			String model = element.getAttributeValue("model");

			if (!element.getAttributeValue("planQty").equals("")) {
				double planQty = Double.valueOf(element
						.getAttributeValue("planQty"));
				newPartTask.setPlanQty(planQty);
			}

			if (!element.getAttributeValue("isCritical").equals("")) {
				int isCritical = Integer.valueOf(element
						.getAttributeValue("isCritical"));
				newPartTask.setIsCritical(isCritical);
			}

			if (!element.getAttributeValue("delayCost").equals("")) {
				int delayCost = Integer.valueOf(element
						.getAttributeValue("delayCost"));
				newPartTask.setDelayCost(delayCost);
			}

			if (!element.getAttributeValue("planGrade").equals("")) {
				int planGrade = Integer.valueOf(element
						.getAttributeValue("planGrade"));
				newPartTask.setPlanGrade(planGrade);
			}

			newPartTask.setPartUid(partUid);
			newPartTask.setBatchNum(batchNum);
			newPartTask.setDrawingId(drawingId);
			newPartTask.setPartName(partName);
			newPartTask.setModel(model);
			newPartTask.setScheme(scheme);

			if (!"".equals(element.getAttributeValue("earlyStart"))) {
				Date earlyStart = formatDate.parse(element
						.getAttributeValue("earlyStart"));
				newPartTask.setEarlyStart(earlyStart);
			}

			if (!"".equals(element.getAttributeValue("lateFinish"))) {
				Date lateFinish = formatDate.parse(element
						.getAttributeValue("lateFinish"));
				newPartTask.setLateFinish(lateFinish);
			}

			if (!"".equals(element.getAttributeValue("actualStart"))) {
				Date actualStart = formatDate.parse(element
						.getAttributeValue("actualStart"));
				newPartTask.setActualStart(actualStart);
			}

			if (!"".equals(element.getAttributeValue("actualFinish"))) {
				Date actualFinish = formatDate.parse(element
						.getAttributeValue("actualFinish"));
				newPartTask.setActualFinish(actualFinish);
			}
			SPartTask partTask = allPartTaskMap.get(strKey);
			// 已经存在就不处理
			if (partTask != null) {
				return;
			} else {
				List<SPartTask> partTaskList = new ArrayList<SPartTask>();
				partTaskList.add(newPartTask);
				// 不要写事件
				schedulePartTaskManager.addPartTask(scheme, newPartTask);
			}
		}

	}

	private void operationTaskCancenGroup(ScheduleScheme scheme, Document doc,
			Map<String, SOperationTask> allOperationTaskMap,
			SimpleDateFormat formatDate) throws Exception {

		Element rootElement = doc.getRootElement();
		String taskUid = rootElement.getAttributeValue("taskUid");
		SOperationTask operationTask = scheme.getAllOperationTaskMap().get(
				taskUid);
		if (operationTask != null
				&& operationTask instanceof SGroupOperationTask) {
			this.scheduleOperationTaskManager
					.cancelGroupTask((SGroupOperationTask) operationTask);
		}
	}

	private void operationTaskCancenGroup(ScheduleScheme scheme,
			Element rootElement,
			Map<String, SOperationTask> allOperationTaskMap,
			SimpleDateFormat formatDate) throws Exception {

		// Element rootElement = doc.getRootElement();
		String taskUid = rootElement.getAttributeValue("taskUid");
		SOperationTask operationTask = scheme.getAllOperationTaskMap().get(
				taskUid);
		if (operationTask != null
				&& operationTask instanceof SGroupOperationTask) {
			this.scheduleOperationTaskManager
					.cancelGroupTask((SGroupOperationTask) operationTask);
		}
	}

	private void operatinoTaskGroup(ScheduleScheme scheme, Document doc,
			Map<String, SOperationTask> allOperationTaskMap,
			SimpleDateFormat formatDate) throws Exception {

		Element rootElement = doc.getRootElement();
		List<Element> elementList = rootElement.getChildren();
		List<SOperationTask> memberTasks = new ArrayList<SOperationTask>();
		for (Element element : elementList) {
			String opKey = element.getAttributeValue("drawingId") + "_"
					+ element.getAttributeValue("batchNum") + "_"
					+ element.getAttributeValue("operationIdDesc");
			String taskUid = element.getAttributeValue("taskUid");
			SOperationTask operationTask = allOperationTaskMap.get(opKey);
			if (operationTask != null) {
				memberTasks.add(operationTask);
			}
		}
		this.scheduleOperationTaskManager.groupTasks(memberTasks, null);

	}

	private void operatinoTaskGroup(ScheduleScheme scheme, Element rootElement,
			Map<String, SOperationTask> allOperationTaskMap,
			SimpleDateFormat formatDate) throws Exception {

		// Element rootElement = doc.getRootElement();
		List<Element> elementList = rootElement.getChildren();
		List<SOperationTask> memberTasks = new ArrayList<SOperationTask>();
		for (Element element : elementList) {
			String opKey = element.getAttributeValue("drawingId") + "_"
					+ element.getAttributeValue("batchNum") + "_"
					+ element.getAttributeValue("operationIdDesc");
			String taskUid = element.getAttributeValue("taskUid");
			SOperationTask operationTask = allOperationTaskMap.get(opKey);
			if (operationTask != null) {
				memberTasks.add(operationTask);
			}
		}
		this.scheduleOperationTaskManager.groupTasks(memberTasks, null);

	}

	private void partTaskPlanInfo(ScheduleScheme scheme, Document doc,
			Map<String, SPartTask> allPartTaskMap, SimpleDateFormat formatDate,
			int eventState, boolean writeLog) throws Exception {

		Element rootElement = doc.getRootElement();
		List<Element> elementList = rootElement.getChildren();
		String strKey = rootElement.getAttributeValue("partUid") + "_"
				+ rootElement.getAttributeValue("batchNum");
		SPartTask partTask = allPartTaskMap.get(strKey);
		if (partTask == null) {
			return;
		}
		// 正向执行，即用新的数据更新工序任务
		if (eventState == 1) {
			for (Element element : elementList) {
				if (!element.getAttributeValue("earlyStart").equals("")) {
					Date earlyStart = formatDate.parse(element
							.getAttributeValue("earlyStart"));
					partTask.setEarlyStart(earlyStart);
				} else {
					partTask.setEarlyStart(null);
				}
				if (!element.getAttributeValue("lateFinish").equals("")) {
					Date lateFinish = formatDate.parse(element
							.getAttributeValue("lateFinish"));
					partTask.setLateFinish(lateFinish);
				} else {
					partTask.setLateFinish(null);
				}
				double planQty = Double.parseDouble(element
						.getAttributeValue("planQty"));
				int isCritical = Integer.parseInt(element
						.getAttributeValue("isCritical"));
				int delayCost = Integer.parseInt(element
						.getAttributeValue("delayCost"));
				int planGrade = Integer.parseInt(element
						.getAttributeValue("planGrade"));
				partTask.setPlanQty(planQty);
				partTask.setIsCritical(isCritical);
				partTask.setDelayCost(delayCost);
				partTask.setPlanGrade(planGrade);
			}
		} else if (eventState == 2) {
			if (!rootElement.getAttributeValue("earlyStart").equals("")) {
				Date earlyStart = formatDate.parse(rootElement
						.getAttributeValue("earlyStart"));
				partTask.setEarlyStart(earlyStart);
			} else {
				partTask.setEarlyStart(null);
			}
			if (!rootElement.getAttributeValue("lateFinish").equals("")) {
				Date lateFinish = formatDate.parse(rootElement
						.getAttributeValue("lateFinish"));
				partTask.setLateFinish(lateFinish);
			} else {
				partTask.setLateFinish(null);
			}
			double planQty = Double.parseDouble(rootElement
					.getAttributeValue("planQty"));
			int isCritical = Integer.parseInt(rootElement
					.getAttributeValue("isCritical"));
			int delayCost = Integer.parseInt(rootElement
					.getAttributeValue("delayCost"));
			int planGrade = Integer.parseInt(rootElement
					.getAttributeValue("planGrade"));
			partTask.setPlanQty(planQty);
			partTask.setIsCritical(isCritical);
			partTask.setDelayCost(delayCost);
			partTask.setPlanGrade(planGrade);
		}
		List<SPartTask> partTaskList = new ArrayList<SPartTask>();
		partTask.setObjectState(BasicModel.OBJECTSTATE_TOBEUPDATED);
		partTaskList.add(partTask);
		if (writeLog) {
			this.schedulePartTaskManager.savePartTask(scheme, partTaskList);
		} else {
			this.schedulePartTaskManager.updatePartTask(scheme, partTask);
		}
	}

	private void partTaskPlanInfo(ScheduleScheme scheme, Element rootElement,
			Map<String, SPartTask> allPartTaskMap, SimpleDateFormat formatDate,
			int eventState, boolean writeLog) throws Exception {

		// Element rootElement = doc.getRootElement();
		List<Element> elementList = rootElement.getChildren();

		// 正向执行，即用新的数据更新任务
		if (eventState == 1) {
			for (Element element : elementList) {
				String strKey = element.getAttributeValue("partUid") + "_"
						+ element.getAttributeValue("batchNum");
				SPartTask partTask = allPartTaskMap.get(strKey);
				if (partTask == null) {
					return;
				}

				if (!element.getAttributeValue("earlyStart").equals("")) {
					Date earlyStart = formatDate.parse(element
							.getAttributeValue("earlyStart"));
					partTask.setEarlyStart(earlyStart);
				} else {
					partTask.setEarlyStart(null);
				}
				if (!element.getAttributeValue("lateFinish").equals("")) {
					Date lateFinish = formatDate.parse(element
							.getAttributeValue("lateFinish"));
					partTask.setLateFinish(lateFinish);
				} else {
					partTask.setLateFinish(null);
				}
				if (!element.getAttributeValue("actualStart").equals("")) {
					Date actualStart = formatDate.parse(element
							.getAttributeValue("actualStart"));
					partTask.setActualStart(actualStart);
				} else {
					partTask.setEarlyStart(null);
				}
				if (!element.getAttributeValue("actualFinish").equals("")) {
					Date actualFinish = formatDate.parse(element
							.getAttributeValue("actualFinish"));
					partTask.setActualFinish(actualFinish);
				} else {
					partTask.setLateFinish(null);
				}

				if (!element.getAttributeValue("planQty").equals("")) {
					double planQty = Double.parseDouble(element
							.getAttributeValue("planQty"));
					partTask.setPlanQty(planQty);
				}
				if (!element.getAttributeValue("completeQty").equals("")) {
					double completeQty = Double.parseDouble(element
							.getAttributeValue("completeQty"));
					partTask.setCompleteQty(completeQty);
				}
				if (!element.getAttributeValue("isCritical").equals("")) {
					int isCritical = Integer.parseInt(element
							.getAttributeValue("isCritical"));
					partTask.setIsCritical(isCritical);
				}

				if (!element.getAttributeValue("delayCost").equals("")) {
					int delayCost = Integer.parseInt(element
							.getAttributeValue("delayCost"));
					partTask.setDelayCost(delayCost);
				}

				if (!element.getAttributeValue("planGrade").equals("")) {
					int planGrade = Integer.parseInt(element
							.getAttributeValue("planGrade"));
					partTask.setPlanGrade(planGrade);
				}

				List<SPartTask> partTaskList = new ArrayList<SPartTask>();
				partTask.setObjectState(BasicModel.OBJECTSTATE_TOBEUPDATED);
				partTaskList.add(partTask);
				if (writeLog) {
					this.schedulePartTaskManager.savePartTask(scheme,
							partTaskList);
				} else {
					this.schedulePartTaskManager.updatePartTask(scheme,
							partTask);
				}
			}
		}
		// else if (eventState == 2) {
		// String strKey = rootElement.getAttributeValue("drawingId") + "_"
		// + rootElement.getAttributeValue("batchNum");
		// SPartTask partTask = allPartTaskMap.get(strKey);
		// if (partTask == null) {
		// return;
		// }
		// if (!rootElement.getAttributeValue("earlyStart").equals("")) {
		// Date earlyStart = formatDate.parse(rootElement
		// .getAttributeValue("earlyStart"));
		// partTask.setEarlyStart(earlyStart);
		// } else {
		// partTask.setEarlyStart(null);
		// }
		// if (!rootElement.getAttributeValue("lateFinish").equals("")) {
		// Date lateFinish = formatDate.parse(rootElement
		// .getAttributeValue("lateFinish"));
		// partTask.setLateFinish(lateFinish);
		// } else {
		// partTask.setLateFinish(null);
		// }
		// double planQty = Double.parseDouble(rootElement
		// .getAttributeValue("planQty"));
		// int isCritical = Integer.parseInt(rootElement
		// .getAttributeValue("isCritical"));
		// int delayCost = Integer.parseInt(rootElement
		// .getAttributeValue("delayCost"));
		// int planGrade = Integer.parseInt(rootElement
		// .getAttributeValue("planGrade"));
		// partTask.setPlanQty(planQty);
		// partTask.setIsCritical(isCritical);
		// partTask.setDelayCost(delayCost);
		// partTask.setPlanGrade(planGrade);
		// }

	}

	private void partTaskSplitBatch(ScheduleScheme scheme, Document doc,
			Map<String, SPartTask> allPartTaskMap, SimpleDateFormat formatDate,
			boolean writeLog) throws Exception {

		Element rootElement = doc.getRootElement();
		String strKey = rootElement.getAttributeValue("partUid") + "_"
				+ rootElement.getAttributeValue("batchNum");
		SPartTask partTask = allPartTaskMap.get(strKey);
		if (partTask != null) {
			List<Element> elements = rootElement.getChildren();
			List<SOperationTask> operationTasks = new ArrayList<SOperationTask>();
			for (Element elem : elements) {
				SOperationTask sOperationTask = new SOperationTask();
				sOperationTask.setBatchNum(elem.getAttributeValue("batchNum"));
				sOperationTask.setPlanQty(Double.valueOf(elem
						.getAttributeValue("planQty")));
				sOperationTask.setOperationIdDesc(elem
						.getAttributeValue("operationIdDesc"));
				operationTasks.add(sOperationTask);
			}
			if (writeLog) {
				this.schedulePartTaskManager.splitBatchWithEvent(partTask,
						operationTasks);
			} else {
				this.schedulePartTaskManager.splitBatch(partTask,
						operationTasks);
			}
		}
	}

	private void partTaskSplitBatch(ScheduleScheme scheme, Element rootElement,
			Map<String, SPartTask> allPartTaskMap, SimpleDateFormat formatDate,
			boolean writeLog) throws Exception {

		// Element rootElement = doc.getRootElement();
		String strKey = rootElement.getAttributeValue("partUid") + "_"
				+ rootElement.getAttributeValue("batchNum");
		SPartTask partTask = allPartTaskMap.get(strKey);
		if (partTask != null) {
			List<Element> elements = rootElement.getChildren();
			List<SOperationTask> operationTasks = new ArrayList<SOperationTask>();
			for (Element elem : elements) {
				SOperationTask refOp = new SOperationTask();
				for (SOperationTask operationTask : partTask
						.getOperationTaskList()) {
					if (elem.getAttributeValue("operationIdDesc").equals(
							operationTask.getOperationIdDesc())) {
						refOp = operationTask;
						break;
					}
				}
				SOperationTask sOperationTask = new SOperationTask();
				sOperationTask.setBatchNum(elem.getAttributeValue("batchNum"));

				sOperationTask.setPlanQty(Double.valueOf(elem
						.getAttributeValue("planQty")));
				sOperationTask.setOperationIdDesc(elem
						.getAttributeValue("operationIdDesc"));
				sOperationTask.setLateFinish(partTask.getLateFinish());
				if (refOp != null) {
					sOperationTask.setOperationId(refOp.getOperationId());
				}

				operationTasks.add(sOperationTask);
			}
			if (writeLog) {
				this.schedulePartTaskManager.splitBatchWithEvent(partTask,
						operationTasks);
			} else {
				this.schedulePartTaskManager.splitBatch(partTask,
						operationTasks);
			}
		}
	}

	private void partTaskCancelSplitBatch(ScheduleScheme scheme, Document doc,
			Map<String, SPartTask> allPartTaskMap, SimpleDateFormat formatDate,
			boolean writeLog) throws Exception {

		Element rootElement = doc.getRootElement();
		String strKey = rootElement.getAttributeValue("partUid") + "_"
				+ rootElement.getAttributeValue("batchNum");
		SPartTask partTask = allPartTaskMap.get(strKey);
		List<SPartTask> splitedBatchs = new ArrayList<SPartTask>();
		if (partTask != null) {
			List<Element> elements = rootElement.getChildren();
			// List<SOperationTask> operationTasks = new
			// ArrayList<SOperationTask>();
			for (Element elem : elements) {
				strKey = rootElement.getAttributeValue("partUid") + "_"
						+ elem.getAttributeValue("batchNum");
				SPartTask chilePartTask = allPartTaskMap.get(strKey);
				if (chilePartTask != null) {
					splitedBatchs.add(chilePartTask);
				}
			}
			if (writeLog) {
				this.schedulePartTaskManager.cancelSplitBatchWithEvent(
						partTask, splitedBatchs);
			} else {
				this.schedulePartTaskManager.cancelSplitBatch(partTask,
						splitedBatchs);
			}

		}

	}

	private void partTaskCancelSplitBatch(ScheduleScheme scheme,
			Element rootElement, Map<String, SPartTask> allPartTaskMap,
			SimpleDateFormat formatDate, boolean writeLog) throws Exception {

		// Element rootElement = doc.getRootElement();
		String strKey = rootElement.getAttributeValue("partUid") + "_"
				+ rootElement.getAttributeValue("batchNum");
		SPartTask partTask = allPartTaskMap.get(strKey);
		List<SPartTask> splitedBatchs = new ArrayList<SPartTask>();
		if (partTask != null) {
			List<Element> elements = rootElement.getChildren();
			// List<SOperationTask> operationTasks = new
			// ArrayList<SOperationTask>();
			for (Element elem : elements) {
				strKey = rootElement.getAttributeValue("partUid") + "_"
						+ elem.getAttributeValue("batchNum");
				SPartTask chilePartTask = allPartTaskMap.get(strKey);
				if (chilePartTask != null) {
					splitedBatchs.add(chilePartTask);
				}
			}
			if (writeLog) {
				this.schedulePartTaskManager.cancelSplitBatchWithEvent(
						partTask, splitedBatchs);
			} else {
				this.schedulePartTaskManager.cancelSplitBatch(partTask,
						splitedBatchs);
			}

		}

	}

	private void partTaskCancelCombineBatch(ScheduleScheme scheme,
			Document doc, Map<String, SPartTask> allPartTaskMap,
			SimpleDateFormat formatDate, boolean writeLog) throws Exception {

		Element rootElement = doc.getRootElement();

		String strKey = rootElement.getAttributeValue("partUid") + "_"
				+ rootElement.getAttributeValue("batchNum");

		SPartTask partTask = allPartTaskMap.get(strKey);
		if (partTask != null) {
			this.schedulePartTaskManager.cancelCombineBatch(scheme, partTask
					.getTaskUid());
			if (writeLog) {
				List<SPartTask> combinedBatchs = partTask.getCombinedBatchs();
				Element taskElement = new Element("PARTTASK_CANCELCOMBINEBATCH");
				taskElement.setAttribute("taskUid", partTask.getTaskUid());
				taskElement.setAttribute("partUid", partTask.getPartUid());
				taskElement.setAttribute("drawingId", partTask.getDrawingId());
				taskElement.setAttribute("partName", partTask.getPartName());
				taskElement.setAttribute("batchNum", partTask.getBatchNum());
				taskElement.setAttribute("planQty", String.valueOf(partTask
						.getPlanQty()));
				for (SPartTask childPpartTask : combinedBatchs) {
					Element splitTaskElement = new Element("splitTask");
					splitTaskElement.setAttribute("taskUid", childPpartTask
							.getTaskUid());
					splitTaskElement.setAttribute("batchNum", childPpartTask
							.getBatchNum());
					splitTaskElement.setAttribute("planQty", String
							.valueOf(childPpartTask.getPlanQty()));
					taskElement.addContent(splitTaskElement);
				}
				this.scheduleEventManager.writeOperLog(scheme,
						ScheduleEvent.EVENTTYPE_PARTTASK_CANCELCOMBINEBATCH,
						taskElement);
			}
		}
	}

	private void partTaskCancelCombineBatch(ScheduleScheme scheme,
			Element rootElement, Map<String, SPartTask> allPartTaskMap,
			SimpleDateFormat formatDate, boolean writeLog) throws Exception {

		// Element rootElement = doc.getRootElement();

		String strKey = rootElement.getAttributeValue("partUid") + "_"
				+ rootElement.getAttributeValue("batchNum");

		SPartTask partTask = allPartTaskMap.get(strKey);
		if (partTask != null) {
			this.schedulePartTaskManager.cancelCombineBatch(scheme, partTask
					.getTaskUid());
			if (writeLog) {
				List<SPartTask> combinedBatchs = partTask.getCombinedBatchs();
				Element taskElement = new Element("PARTTASK_CANCELCOMBINEBATCH");
				taskElement.setAttribute("taskUid", partTask.getTaskUid());
				taskElement.setAttribute("partUid", partTask.getPartUid());
				taskElement.setAttribute("drawingId", partTask.getDrawingId());
				taskElement.setAttribute("partName", partTask.getPartName());
				taskElement.setAttribute("batchNum", partTask.getBatchNum());
				taskElement.setAttribute("planQty", String.valueOf(partTask
						.getPlanQty()));
				for (SPartTask childPpartTask : combinedBatchs) {
					Element splitTaskElement = new Element("splitTask");
					splitTaskElement.setAttribute("taskUid", childPpartTask
							.getTaskUid());
					splitTaskElement.setAttribute("batchNum", childPpartTask
							.getBatchNum());
					splitTaskElement.setAttribute("planQty", String
							.valueOf(childPpartTask.getPlanQty()));
					taskElement.addContent(splitTaskElement);
				}
				this.scheduleEventManager.writeOperLog(scheme,
						ScheduleEvent.EVENTTYPE_PARTTASK_CANCELCOMBINEBATCH,
						taskElement);
			}
		}
	}

	private void partTaskComnineBatch(ScheduleScheme scheme, Document doc,
			Map<String, SPartTask> allPartTaskMap, SimpleDateFormat formatDate,
			boolean writeLog) throws Exception {
		Element rootElement = doc.getRootElement();
		List<Element> elements = rootElement.getChildren();
		List<SPartTask> partTasks = new ArrayList<SPartTask>();
		for (Element elem : elements) {
			String taskUid = elem.getAttributeValue("taskUid");
			SPartTask partTask = scheme.getAllPartTaskMap().get(taskUid);
			partTasks.add(partTask);
		}
		if (writeLog) {
			// 写日志
			String batchNum = "";
			int planQty = 0;
			for (SPartTask partTask : partTasks) {
				batchNum += partTask.getBatchNum() + ",";
				planQty += partTask.getPlanQty();
			}
			batchNum = batchNum.substring(0, batchNum.length() - 1);
			SPartTask newTask = partTasks.get(0);

			this.schedulePartTaskManager.combineBatch(partTasks, -1);

			Element taskElement = new Element("PARTTASK_COMBINEBATCH");
			taskElement.setAttribute("taskUid", newTask.getTaskUid());
			taskElement.setAttribute("batchNum", batchNum);
			taskElement.setAttribute("partUid", newTask.getPartUid());
			taskElement.setAttribute("drawingId", newTask.getDrawingId());
			taskElement.setAttribute("partName", newTask.getPartName());
			taskElement.setAttribute("planQty", String.valueOf(planQty));
			for (SPartTask partTask : partTasks) {
				Element combineTaskElement = new Element("combineTask");
				combineTaskElement.setAttribute("batchNum", partTask
						.getBatchNum());
				combineTaskElement.setAttribute("planQty", String
						.valueOf(partTask.getPlanQty()));
				combineTaskElement.setAttribute("taskUid", partTask
						.getTaskUid());
				taskElement.addContent(combineTaskElement);
			}
			this.scheduleEventManager.writeOperLog(scheme,
					ScheduleEvent.EVENTTYPE_PARTTASK_COMBINEBATCH, taskElement);
		} else {
			SPartTask newPartTask = this.schedulePartTaskManager.combineBatch(
					partTasks, 0);
		}

		// newPartTask.setBatchNum(rootElement.getAttributeValue("batchNum"));

	}

	private void partTaskComnineBatch(ScheduleScheme scheme,
			Element rootElement, Map<String, SPartTask> allPartTaskMap,
			SimpleDateFormat formatDate, boolean writeLog) throws Exception {
		// Element rootElement = doc.getRootElement();
		List<Element> elements = rootElement.getChildren();
		List<SPartTask> partTasks = new ArrayList<SPartTask>();
		for (Element elem : elements) {
			String partKey = rootElement.getAttributeValue("drawingId") + "_"
					+ elem.getAttributeValue("batchNum");
			SPartTask partTask = allPartTaskMap.get(partKey);
			partTasks.add(partTask);
		}
		if (writeLog) {
			// 写日志
			String batchNum = "";
			int planQty = 0;
			for (SPartTask partTask : partTasks) {
				batchNum += partTask.getBatchNum() + ",";
				planQty += partTask.getPlanQty();
			}
			batchNum = batchNum.substring(0, batchNum.length() - 1);
			SPartTask newTask = partTasks.get(0);

			this.schedulePartTaskManager.combineBatch(partTasks, -1);

			Element taskElement = new Element("PARTTASK_COMBINEBATCH");
			taskElement.setAttribute("taskUid", newTask.getTaskUid());
			taskElement.setAttribute("batchNum", batchNum);
			taskElement.setAttribute("partUid", newTask.getPartUid());
			taskElement.setAttribute("drawingId", newTask.getDrawingId());
			taskElement.setAttribute("partName", newTask.getPartName());
			taskElement.setAttribute("planQty", String.valueOf(planQty));
			for (SPartTask partTask : partTasks) {
				Element combineTaskElement = new Element("combineTask");
				combineTaskElement.setAttribute("batchNum", partTask
						.getBatchNum());
				combineTaskElement.setAttribute("planQty", String
						.valueOf(partTask.getPlanQty()));
				combineTaskElement.setAttribute("taskUid", partTask
						.getTaskUid());
				taskElement.addContent(combineTaskElement);
			}
			this.scheduleEventManager.writeOperLog(scheme,
					ScheduleEvent.EVENTTYPE_PARTTASK_COMBINEBATCH, taskElement);
		} else {
			SPartTask newPartTask = this.schedulePartTaskManager.combineBatch(
					partTasks, 0);
		}

		// newPartTask.setBatchNum(rootElement.getAttributeValue("batchNum"));

	}

	/**
	 * 要根据int型参数来判断是正向执行还是逆向执行
	 * 
	 * @param scheme
	 * @param doc
	 * @param allOperationTaskMap
	 * @param formatDate
	 * @param eventState
	 * @throws Exception
	 */
	private void operationTaskPlanInfo(ScheduleScheme scheme, Document doc,
			Map<String, SOperationTask> allOperationTaskMap,
			SimpleDateFormat formatDate, int eventState, boolean writeLog)
			throws Exception {

		Element rootElement = doc.getRootElement();
		List<Element> elementList = rootElement.getChildren();
		String strKey = rootElement.getAttributeValue("partUid") + "_"
				+ rootElement.getAttributeValue("batchNum") + "_"
				+ rootElement.getAttributeValue("operationIdDesc");
		SOperationTask operationTask = allOperationTaskMap.get(strKey);
		if (operationTask == null) {
			return;
		}
		SOperationTask newOpTask = new SOperationTask();
		newOpTask.setTaskUid(operationTask.getTaskUid());
		newOpTask.setPartUid(operationTask.getPartUid());
		newOpTask.setBatchNum(operationTask.getBatchNum());
		newOpTask.setOperationIdDesc(operationTask.getOperationIdDesc());
		newOpTask.setTaskName(operationTask.getTaskName());
		newOpTask.setDrawingId(operationTask.getDrawingId());

		// 正向执行，即用新的数据更新工序任务
		if (eventState == 1) {

			for (Element element : elementList) {
				if (!element.getAttributeValue("earlyStart").equals("")) {
					Date earlyStart = formatDate.parse(element
							.getAttributeValue("earlyStart"));
					newOpTask.setEarlyStart(earlyStart);
				} else {
					newOpTask.setEarlyStart(null);
				}
				if (!element.getAttributeValue("lateFinish").equals("")) {
					Date lateFinish = formatDate.parse(element
							.getAttributeValue("lateFinish"));
					newOpTask.setLateFinish(lateFinish);
				} else {
					newOpTask.setLateFinish(null);
				}
				double planQty = Double.parseDouble(element
						.getAttributeValue("planQty"));
				double completeQty = Double.parseDouble(element
						.getAttributeValue("completeQty"));
				double estiRunTime = Double.parseDouble(element
						.getAttributeValue("estiRunTime"));
				double estiPreTime = Double.parseDouble(element
						.getAttributeValue("estiPreTime"));
				String succOperationStr = element
						.getAttributeValue("succOperationStr");
				Integer locked = Integer.valueOf(element
						.getAttributeValue("locked"));
				newOpTask.setPlanQty(planQty);
				newOpTask.setCompleteQty(completeQty);
				newOpTask.setEstiRunTime(estiRunTime);
				newOpTask.setEstiPreTime(estiPreTime);
				newOpTask.setSuccOperationStr(succOperationStr);
				newOpTask.setLocked(locked);
			}

		} else if (eventState == 2) {
			if (!rootElement.getAttributeValue("earlyStart").equals("")) {
				Date earlyStart = formatDate.parse(rootElement
						.getAttributeValue("earlyStart"));
				newOpTask.setEarlyStart(earlyStart);
			} else {
				newOpTask.setEarlyStart(null);
			}
			if (!rootElement.getAttributeValue("lateFinish").equals("")) {
				Date lateFinish = formatDate.parse(rootElement
						.getAttributeValue("lateFinish"));
				newOpTask.setLateFinish(lateFinish);
			} else {
				newOpTask.setLateFinish(null);
			}
			double planQty = Double.parseDouble(rootElement
					.getAttributeValue("planQty"));
			double completeQty = Double.parseDouble(rootElement
					.getAttributeValue("completeQty"));
			double estiRunTime = Double.parseDouble(rootElement
					.getAttributeValue("estiRunTime"));
			double estiPreTime = Double.parseDouble(rootElement
					.getAttributeValue("estiPreTime"));
			String succOperationStr = rootElement
					.getAttributeValue("succOperationStr");
			Integer locked = Integer.valueOf(rootElement
					.getAttributeValue("locked"));
			newOpTask.setPlanQty(planQty);
			newOpTask.setCompleteQty(completeQty);
			newOpTask.setEstiRunTime(estiRunTime);
			newOpTask.setEstiPreTime(estiPreTime);
			newOpTask.setSuccOperationStr(succOperationStr);
			newOpTask.setLocked(locked);
		}
		List<SOperationTask> opTaskList = new ArrayList<SOperationTask>();
		newOpTask.setObjectState(BasicModel.OBJECTSTATE_TOBEUPDATED);
		opTaskList.add(newOpTask);
		if (writeLog) {
			scheduleOperationTaskManager.saveOperationTask(scheme,
					operationTask.getParentTaskUid(), opTaskList, true);
		} else {
			scheduleOperationTaskManager.updateOperationTask(scheme, newOpTask);
		}
	}

	private void operationTaskPlanInfo(ScheduleScheme scheme,
			Element rootElement,
			Map<String, SOperationTask> allOperationTaskMap,
			SimpleDateFormat formatDate, int eventState, boolean writeLog)
			throws Exception {

		// Element rootElement = doc.getRootElement();
		List<Element> elementList = rootElement.getChildren();
		for (Element element : elementList) {
			String strKey = element.getAttributeValue("drawingId") + "_"
					+ element.getAttributeValue("batchNum") + "_"
					+ element.getAttributeValue("operationIdDesc");
			SOperationTask operationTask = allOperationTaskMap.get(strKey);
			if (operationTask == null) {
				return;
			}
			SOperationTask newOpTask = new SOperationTask();
			newOpTask.setTaskUid(operationTask.getTaskUid());
			// newOpTask.setPartUid(operationTask.getPartUid());
			newOpTask.setBatchNum(operationTask.getBatchNum());
			newOpTask.setOperationIdDesc(operationTask.getOperationIdDesc());
			newOpTask.setTaskName(operationTask.getTaskName());
			newOpTask.setDrawingId(operationTask.getDrawingId());

			if (!element.getAttributeValue("locked").equals("")) {
				int locked = Integer.parseInt(element
						.getAttributeValue("locked"));
				newOpTask.setLocked(locked);
			} else {
				newOpTask.setLocked(operationTask.getLocked());
			}

			if (!element.getAttributeValue("succOperationStr").equals("")) {
				String succOperationStr = element
						.getAttributeValue("succOperationStr");
				newOpTask.setSuccOperationStr(succOperationStr);
			} else {
				newOpTask.setSuccOperationStr(operationTask
						.getSuccOperationStr());
			}

			if (!element.getAttributeValue("operationId").equals("")) {
				float operationId = Integer.parseInt(element
						.getAttributeValue("operationId"));
				newOpTask.setOperationId(operationId);
			} else {
				newOpTask.setOperationId(operationTask.getOperationId());
			}

			if (!element.getAttributeValue("masterShop").equals("")) {
				String masterShop = element.getAttributeValue("masterShop");
				newOpTask.setMasterShop(masterShop);
			} else {
				newOpTask.setMasterShop(operationTask.getMasterShop());
			}
			if (!element.getAttributeValue("masterShopName").equals("")) {
				String masterShopName = element
						.getAttributeValue("masterShopName");
				newOpTask.setMasterShopName(masterShopName);
			} else {
				newOpTask.setMasterShopName(operationTask.getMasterShopName());
			}

			if (!element.getAttributeValue("workCenterUid").equals("")) {
				String workCenterUid = element
						.getAttributeValue("workCenterUid");
				newOpTask.setWorkCenterUid(workCenterUid);
				newOpTask.setDeviceClass(workCenterUid);
			} else {
				newOpTask.setWorkCenterUid(operationTask.getWorkCenterUid());
				newOpTask.setDeviceClass(operationTask.getDeviceClass());
			}
			if (!element.getAttributeValue("workCenterName").equals("")) {
				String workCenterName = element
						.getAttributeValue("workCenterName");
				newOpTask.setDeviceClassName(workCenterName);
			} else {
				newOpTask
						.setDeviceClassName(operationTask.getDeviceClassName());
			}

			if (!element.getAttributeValue("calUid").equals("")) {
				String calUid = element.getAttributeValue("calUid");
				newOpTask.setCalUid(calUid);
			} else {
				newOpTask.setCalUid(operationTask.getCalUid());
			}

			if (!element.getAttributeValue("deptId").equals("")) {
				String deptId = element.getAttributeValue("deptId");
				newOpTask.setDeptUid(deptId);
			} else {
				newOpTask.setDeptUid(operationTask.getDeptUid());
			}

			if (!element.getAttributeValue("deviceSeq").equals("")) {
				int deviceSeq = Integer.parseInt(element
						.getAttributeValue("deviceSeq"));
				newOpTask.setDeviceSeq(deviceSeq);
			} else {
				newOpTask.setDeviceSeq(operationTask.getDeviceSeq());
			}

			if (!element.getAttributeValue("earlyStart").equals("")) {
				Date earlyStart = formatDate.parse(element
						.getAttributeValue("earlyStart"));
				newOpTask.setEarlyStart(earlyStart);
			} else {
				newOpTask.setEarlyStart(operationTask.getEarlyStart());
			}
			if (!element.getAttributeValue("lateFinish").equals("")) {
				Date lateFinish = formatDate.parse(element
						.getAttributeValue("lateFinish"));
				newOpTask.setLateFinish(lateFinish);
			} else {
				newOpTask.setLateFinish(operationTask.getLateFinish());
			}

			if (!element.getAttributeValue("baseStart").equals("")) {
				Date baseStart = formatDate.parse(element
						.getAttributeValue("baseStart"));
				newOpTask.setBaseStart(baseStart);
			} else {
				newOpTask.setBaseStart(operationTask.getBaseStart());
			}
			if (!element.getAttributeValue("baseFinish").equals("")) {
				Date baseFinish = formatDate.parse(element
						.getAttributeValue("baseFinish"));
				newOpTask.setBaseFinish(baseFinish);
			} else {
				newOpTask.setBaseFinish(operationTask.getBaseFinish());
			}

			if (!element.getAttributeValue("planQty").equals("")) {
				double planQty = Double.parseDouble(element
						.getAttributeValue("planQty"));
				newOpTask.setPlanQty(planQty);
			} else {
				newOpTask.setPlanQty(operationTask.getPlanQty());
			}
			if (!element.getAttributeValue("completeQty").equals("")) {
				double completeQty = Double.parseDouble(element
						.getAttributeValue("completeQty"));
				newOpTask.setCompleteQty(completeQty);
			} else {
				newOpTask.setCompleteQty(operationTask.getCompleteQty());
			}

			if (!element.getAttributeValue("estiRunTime").equals("")) {
				double estiRunTime = Double.parseDouble(element
						.getAttributeValue("estiRunTime"));
				newOpTask.setEstiRunTime(estiRunTime);
			} else {
				newOpTask.setEstiRunTime(operationTask.getEstiRunTime());
			}

			if (!element.getAttributeValue("estiPreTime").equals("")) {
				double estiPreTime = Double.parseDouble(element
						.getAttributeValue("estiPreTime"));
				newOpTask.setEstiPreTime(estiPreTime);
			} else {
				newOpTask.setEstiPreTime(operationTask.getEstiPreTime());
			}

			List<SOperationTask> opTaskList = new ArrayList<SOperationTask>();
			newOpTask.setObjectState(BasicModel.OBJECTSTATE_TOBEUPDATED);
			opTaskList.add(newOpTask);
			if (writeLog) {
				scheduleOperationTaskManager.saveOperationTask(scheme,
						operationTask.getParentTaskUid(), opTaskList, true);
			} else {
				scheduleOperationTaskManager.updateOperationTask(scheme,
						newOpTask);
			}
		}

		// 正向执行，即用新的数据更新工序任务

	}

	 
	public String getEventPara(List<ScheduleEvent> eventList, String eventPara,
			ScheduleScheme scheme) {
		String paraValueString = "";
		if (eventList != null && eventList.size() > 0) {
			for (ScheduleEvent scheduleEvent : eventList) {
				try {
					paraValueString = this.scheduleEventManager.getEventPara(
							scheduleEvent, eventPara, scheme);
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		}
		return paraValueString;
	}
}